使用get请求或post请求可以传递简单的参数,但要上传图片到服务器,就要多做一些工作了,如下代码片段利用post请求可成功上传图片到服务器:
QNetworkRequest request; request.setUrl(m_strServerAddr); QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); QHttpPart imagePart; imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg"));//如果是png图片填image/png imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"image\"; filename=\"image.jpg\"")); // imagePart.setRawHeader("Content-ID", "my@content.id"); // 添加任何你喜欢的 headers QFile *file = new QFile("image.jpg"); file->open(QIODevice::ReadOnly); imagePart.setBodyDevice(file); multiPart->append(imagePart); m_pNetWorkManager->post(request, multiPart);
参考:
Qt 之 QHttpPart 和 QHttpMultiPart - CSDN博客 https://blog.csdn.net/liang19890820/article/details/52548717