[SOLVED] Error during multipart upload using Qt


I am trying to upload a file using QNetworkAccessManager, but I always get an error (Error transferring url – server replied: Bad Request). Below is my code

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);

However running this python script, which should do the same thing, works.

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);


The problem was fixed by adding a data += "\r\n" at the end of the data.

Answered By – reckless

Answer Checked By – Timothy Miller (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *