将 tiff 图像转换为字符串,以作为二进制应用程序/八位字节流 (C++) 发布

Convert tiff image into String to be posted as binary application/octet-stream (C++)

本文关键字:字节流 八位 应用程序 C++ 发布 转换 图像 tiff 字符串 二进制      更新时间:2023-10-16

我正在使用C++套接字向服务器发送包含TIFF图像的HTTP Multipart POST。此服务器需要二进制八位字节流。

我尝试的是这样的:

// Convert out data into a string that can be appended to the body
std::ifstream fin(fileName, std::ios::binary);
std::ostringstream ostrm;
ostrm << fin.rdbuf();
string data(ostrm.str());

不幸的是,我只得到 II*,而数据应该更长。我的猜测是数据包含一个 NULL 字符,这C++认为字符串已经完成。关于如何解决此问题的任何想法?

如果有帮助,这是我的身体构造代码:

string constructBody(string batchId, string fileString, string fileName) {
    string body;
    string CRLF = "rn";
    // first we add the args
    body.append("--" + string(BOUNDARY) + CRLF);
    body.append("Content-Disposition: form-data; name="batch_id"" + CRLF);
    body.append(CRLF);
    body.append(batchId + CRLF);
    body.append("--" + string(BOUNDARY) + CRLF);
    // now we add the file
    body.append("Content-Disposition: form-data; name="front"; filename="" + string(fileName) + """ + CRLF);
    body.append("Content-Type: application/octet-stream" + CRLF);
    body.append("Content-Transfer-Encording: binary" + CRLF);
    body.append(CRLF);
    body.append(fileString + CRLF);
    body.append("--" + string(BOUNDARY) + "--" + CRLF);
    body.append(CRLF);
    return body;
}

这是发布代码:

string body = constructBody(batchId, data, "Front.tif");
char header[1024];
sprintf(header, "POST %s HTTP/1.1rn"
    "Host: %srn"
    "Content-Length: %drn"
    "Connection: Keep-Alivern"
    "Content-Type: multipart/form-data; boundary=%srn"
    "Accept-Charset: utf-8rnrn", RECEIVER, IP, strlen(body.c_str()), BOUNDARY);
int p = send(dataSock, header, strlen(header), 0);
int k = send(dataSock, body.c_str(), strlen(body.c_str()), 0);

提前感谢!

不能使用使用 null 作为字符串终止符的函数:

int k = send(dataSock, body.c_str(), strlen(body.c_str()), 0);

您正在使用上面的strlen。 这是不正确的。

解决此问题的方法是将length()函数用于std::string

int k = send(dataSock, body.c_str(), body.length()), 0);

您在其他位置犯了相同的错误,例如在创建标头时:

"Accept-Charset: utf-8rnrn", RECEIVER, IP, strlen(body.c_str()), BOUNDARY);

应该是:

"Accept-Charset: utf-8rnrn", RECEIVER, IP, body.length(), BOUNDARY);