C++中的图像HTTP上载已损坏
Image HTTP upload in C++ is corrupted
我试图使用Windows套接字HTTP将PNG图像上传到PHP脚本。一切似乎都很好,但当我试图在Windows Paint中打开我的图像时,我收到了一条错误消息:
这不是一个有效的位图文件。
我不知道怎么了。我对HTTP头字段有点陌生,所以我的猜测是头可能是错误的。是什么原因造成的?
C++代码(原始C++粘贴链接):
#include <iostream>
#include <winsock2.h>
#include <string>
#include <fstream>
#include "windows.h"
#include "stdio.h"
using namespace std;
#define PORT 80
#define IP "127.0.0.1"
#define HOST "locahost"
#define RECEIVER "/up.php"
#define COMPNAME "compname"
#define PROGRAM "program"
#define FILENAME "file"
#define BOUNDARY "----------boundary"
#define DUMMY_DATA "c2FzYXNhc2FzZGRmZGZkY2Q="
#define DUMMY_FILE "ok.png"
//------------------------------------
string constructBody(string args[2], string file[2]);
string readFile(string fileName);
//------------------------------------
int main() {
// initiate the socket!
SOCKET dataSock;
WSADATA wsaData;
int error = WSAStartup(0x0202, &wsaData);
if (error != 0) {
WSACleanup();
exit(1); // oh shit, this shouldn't happen!
}
// all internets, engage!
SOCKADDR_IN target;
target.sin_family = AF_INET;
target.sin_port = htons(PORT);
target.sin_addr.s_addr = inet_addr(IP);
dataSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (dataSock == INVALID_SOCKET) {
exit(1); // Houston, we have a problem!
}
connect(dataSock, (SOCKADDR*)&target, sizeof(target));
string programNames[5][2] = {{"Browser", "Mozilla"}};
string file[2] = {FILENAME, "Default.txt"};
for (int i = 0; i < 1; i++) {
printf("Sending data for %sn", (programNames[i][1]).c_str());
string body = constructBody(programNames[i], file);
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"
"rn", RECEIVER, IP, strlen(body.c_str()), BOUNDARY);
// printf("%snn", header);
int p = send(dataSock, header, strlen(header), 0);
// printf("p == %dn", p);
int k = send(dataSock, body.c_str(), strlen(body.c_str()), 0);
// printf("k == %dn", k);
char buff[1024];
recv(dataSock, buff, 1024, 0);
printf("%snn", buff);
}
closesocket(dataSock);
WSACleanup();
}
string readFile(string fileName) {
string fileContents;
ifstream tmp(fileName.c_str());
getline(tmp, fileContents);
tmp.close();
return fileContents;
}
string constructBody(string args[2], string file[2]) {
string body;
string CRLF = "rn";
// first we add the args
body.append("--"+string(BOUNDARY)+CRLF);
body.append("Content-Disposition: form-data; name=""+string(COMPNAME)+"""+CRLF);
body.append(CRLF);
body.append(args[0]+CRLF);
body.append("--"+string(BOUNDARY)+CRLF);
body.append("Content-Disposition: form-data; name=""+string(PROGRAM)+"""+CRLF);
body.append(CRLF);
body.append(args[1]+CRLF);
// now we add the file
body.append("--"+string(BOUNDARY)+CRLF);
body.append("Content-Disposition: form-data; name=""+string(FILENAME)+""; filename=""+string(DUMMY_FILE)+"""+CRLF);
body.append("Content-Type: media-type"+CRLF);
body.append(CRLF);
body.append(DUMMY_DATA+CRLF);
body.append("--"+string(BOUNDARY)+"--"+CRLF);
body.append(CRLF);
// printf(body.c_str()); exit(0);
return body;
}
PHP代码(原始PHP pastebin链接):
<?php
/* ===== CONSTANTS ===== */
$ROOT_DIR = 'FILES';
$COMPUTER_NAME = 'compname';
$PROGRAM = 'program';
$FILENAME = 'file';
$CHUNK_SIZE = 1024;
/* ===================== */
//=====================================
/**
Function that gets current time and formats it into pretty looking date
*/
function makeDate() {
return strftime('%Y-%m-%d, %H.%M');
}
//=====================================
// check here if the parameters are set. If it's not then it's safe to say some one is snooping around...
if (isset($_POST[$COMPUTER_NAME], $_POST[$PROGRAM], $_FILES[$FILENAME])) {
// construct a full path and create it
$fullPath = $ROOT_DIR.''.$_POST[$COMPUTER_NAME].''.$_POST[$PROGRAM].''.makeDate();
mkdir($fullPath, 0777, true);
// move the files and rename them as temporary
$filename = $_FILES[$FILENAME]['name'];
move_uploaded_file(($_FILES[$FILENAME]['tmp_name']), $fullPath.''.$filename.'.tmp');
// decode received files
$src = fopen($fullPath.''.$filename.'.tmp', 'rb');
$dst = fopen($fullPath.''.$filename, 'wb');
while (!feof($src)) {
fwrite($dst, base64_decode(fread($src, $CHUNK_SIZE)));
}
fclose($dst);
fclose($src);
unlink($fullPath.''.$filename.'.tmp'); // remove the temp file after decoding it
echo 'OK!';
} else {
echo 'oh no :(';
}
//=====================================
?>
至少,C++代码将.png文件作为文本文件读取,并将内容视为以null结尾的字符串。它似乎只读到了第一行的结尾。您要做的是对.png文件进行二进制读取。
尝试更改readFile()
函数以使用与本例相同的二进制读取功能。
请注意,在该示例中,首先读取文件大小,以便分配足够大小的缓冲区。您可能不想手动处理缓冲区管理,因此可以选择使用vector<char>
,相关的内存资源将为您分配/释放。有关vector<>
的参考指南,请参阅此链接。
像这样的东西可能更接近你想要的:
bool readFile(string fileName, vector<char> &fileContents) {
vector<char> fileContents;
std::ifstream is (fileName.c_str(), std::ifstream::binary);
bool success = is;
if (success) {
// get length of file:
is.seekg (0, is.end);
int length = is.tellg();
is.seekg (0, is.beg);
fileContents.resize(length);
is.read(fileContents, length);
is.close();
}
return success;
}
有了这些更改,您将不得不更改对readFile()
的调用方式。值得注意的是,在您发布的代码中从未实际调用过readFile()
,因此在constructBody()
中会有一个点,您可以声明一个fileContents
变量并调用readFile()
来填充它
考虑使用readFile()
:
vector<char> fileContents;
bool success = readFile(filename, fileContents);
稍后在相同的函数中,您将希望将fileContents
输出到body
缓冲区。
与fileContents
一样,body
变量不应该是string
,以避免意外的null终止。在这种情况下,最好也使用vector<char>
,并且需要更新对body.append()
的所有调用,以正确地附加内容和行结尾。它应该很简单,但仍需要一些额外的工作才能完成。
我还没有深入研究PHP代码,因为这将是您在阅读和发送.png文件时遇到的第一个主要问题。不管是别的什么,完全。您需要确保PHP代码接收到的文件内容与原始.png文件的实际内容相匹配,并且可以提供调试输出来实现这一点。在它们匹配之前,这可能仍然是C++代码中的一个问题。
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 为什么C中的通用链表中存储的数据已损坏
- gdb错误:Backtrace已停止:上一帧与此帧相同(堆栈已损坏?)
- 变量周围的堆栈'...'已损坏
- 运行时检查失败 #2 变量"A"周围的堆栈已损坏
- 两个垫子的 OpenCV 数据是相同的,但使用 Mat::at 检索时的值已损坏
- 如何仅隐式加载已签名的 DLL
- 运行时检查失败 #2 - 变量"e"周围的堆栈已损坏。发生
- 变量周围的堆栈'sortArray'已损坏
- 变量周围的堆栈'folderPath'已损坏
- 在为 iOS 构建 aws-sdk-cpp 时,cmake 上的 CXX 编译器错误已损坏
- 运行时检查失败 #2 - 变量周围的堆栈'...'已损坏
- AES-128 CFB-8解密的前16个字节已损坏
- 图像在本地主机上显示已损坏
- UART上的串行数据已损坏
- SFML图像加载在发布版本上失败 - 文件名损坏
- C++中的图像HTTP上载已损坏
- TCP/IP IOCP接收到的数据有时已损坏-Windows上的Visual C++
- 运行时检查失败 #2 - mfc 应用程序上变量"osvi"周围的堆栈已损坏
- 堆在realloc()上已损坏