QT上传(PUT)一个文件 [英] QT upload (PUT) a file

查看:2058
本文介绍了QT上传(PUT)一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用QT将文件上传到Web服务器。网络服务器使用以下请求接受文件:

I am using QT to upload a file to a web server. The web server accepts files using the following request:

curl -X POST -H 'Content-Type:multipart/form-data' 
-H 'Authorization: Token <token>' 
-F 'file=@file_to_upload.txt' 
https://some.web.site/api/v2/files/contents/

我大致使用这个QT调用来尝试完成同样的操作:

I am using roughly this QT calls to try to accomplish the same:

QHttpMultiPart multiPart(QHttpMultiPart::FormDataType);
QHttpPart filePart;

file.open(QIODevice::ReadOnly)

filePart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data");
filePart.setBodyDevice(file);
multiPart.append(filePart);

QNetworkAccessManager mgr;
QNetworkRequest req(url);
req.setRawHeader("Authorization", ("Token <token>").data());

QNetworkReply * reply(mgr.put(req, &multiPart));

现在这是我从服务器获得的:

Right now this is what I get from the server:

File object is missing or invalid.

与curl命令相比,有人可以停止QT部分丢失吗?我猜想qt缺少一些步骤,curl在幕后。

Can someone stop what the QT part is missing compared to the curl command? I would guess qt is missing some step that curl does behind the scenes. I would rather prefer a solution that does not involve me putting the whole request together manually.

推荐答案

你应该做一些代码修改:

You should make some code modifications:

file.open(QIODevice::ReadOnly);

//add next lines
filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/zip")); //or whatever type of your file.
filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\""));
filePart.setHeader(QNetworkRequest::ContentLengthHeader, file.size());

//and your other code
filePart.setBodyDevice(file);
multiPart.append(filePart);

并注意使用 curl make POST 请求,但使用 Qt - put 。因此,也要用最后一行代替:

And also take attention that with curl you make POST request but with Qt - put. So also replace last line with this:

QNetworkReply * reply = mgr.post(req, &multiPart);

这篇关于QT上传(PUT)一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆