我正在尝试使用QNetworkAccessManager上传文件,但我总是收到错误(错误传输网址 - 服务器回复:错误请求)。以下是我的代码
QString name = "Simple.txt";
QString type = "text/plain; charset=utf-8";
QString uploadUrl = "myuploadUrl";
// setup the multipart request
QString bound="---------------------------723690991551375881941828858";
QByteArray data(QString("--"+bound+"\r\n").toLatin1());
// write the file using standard method for multipart file upload
data += "Content-Disposition: form-data; name=\"file\"; filename=\""+name.toLatin1()+"\"\r\n";
data += "Content-Type: "+type.toLatin1()+"\r\n\r\n";
data += "Hello, I am simple file";
data += "\r\n";
data += "--" + bound;
qDebug() << data;
// make the request with appropriate headers
QNetworkRequest request(QUrl(uploadUrl));
request.setRawHeader(QByteArray("Content-Type"),QString("multipart/form-data; boundary=" + bound).toLatin1());
request.setRawHeader(QByteArray("Content-Length"), QString::number(data.length()).toLatin1());
QNetworkReply *reply = networkManager->post(request,data);
QObject::connect(reply, &QNetworkReply::finished, this, FileUploader::requestFinished);
然而,运行这个应该做同样事情的python脚本有效。
import requests
import json
file_name = "Simple.txt"
uploadUrl = "myUploadUrl";
resp = requests.post(uploadUrl, data=r["data"], files={"file": open(file_name, "rb")})
print (resp);
答案 0 :(得分:0)
通过在数据末尾添加data += "\r\n"
来解决问题。