使用过程中遇到的问题,首先参考QT官方例子
QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
QHttpPart textPart;
textPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"text\""));
textPart.setBody("my text");
QHttpPart imagePart;
imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg"));
imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"image\""));
QFile *file = new QFile("image.jpg");
file->open(QIODevice::ReadOnly);
imagePart.setBodyDevice(file);
file->setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart
multiPart->append(textPart);
multiPart->append(imagePart);
QUrl url("http://my.server.tld");
QNetworkRequest request(url);
QNetworkAccessManager manager;
QNetworkReply *reply = manager.post(request, multiPart);
multiPart->setParent(reply); // delete the multiPart with the reply
// here connect signals etc.
- 发现测试不通过,最后看到“Usually, you do not need to generate a boundary yourself; upon construction the boundary is initiated with the string "boundary_.oOo._" followed by random characters, and provides enough uniqueness to make sure it does not occur inside the parts itself.”翻译:通常,您不需要自己生成边界。 在构造时,边界以字符串“ boundary_.oOo._”开头,后跟随机字符,并提供足够的唯一性以确保它不会在该方法内部重复。最够添加如下代码解决
QString boundary = "boundary_.oOo._MTA0NzE=MjcyNDY=ODk2Ng==;";
multipart->setBoundary(boundary .toLatin1());
request->setHeader(QNetworkRequest::ContentTypeHeader,"multipart/form-data;boundary="+boundary );
-
多个文件上传时改成 multipart/form-data