我有一个Go API,可以保存客户端发送的图像。我知道当POST请求来自HTML表单时,Go代码可以正常工作。 从我的Qt C ++客户端发送多部分发布请求时,服务器返回错误
http:没有这样的文件
在客户端,我有一个QPixmap,我转换为QByteArray,然后我发送,但不知怎的,我从Go得到了这个错误。我知道当我删除
时,客户端发送的数据长度会减少multi_part->append(image_part);
所以应该发送QPixmap。
转到代码:
func apiUploadHandler(w http.ResponseWriter, req *http.Request) {
if req.Method == "POST" {
req.ParseMultipartForm(0)
fmt.Printf("%v %v %v", req.RemoteAddr, req.ContentLength, req.Body)
file, fileheader, err := req.FormFile("image")
if err != nil {
cio.PrintMessage(1, err.Error())
return
}
defer file.Close()
var id string
created := false
for created != true {
id = generateImageID()
err = db.CheckIfImageIDInUse(id)
if err != nil {
if err.Error() == "Image ID '"+id+"' exists.'" {
created = false
continue
} else {
created = false
cio.PrintMessage(1, err.Error())
return
}
}
created = true
}
filePath := fsys.ImgStoragePath + id + "." + strings.Split(fileheader.Filename, ".")[1]
err = db.StoreImage(id, strings.Split(fileheader.Filename, ".")[0] /*image name*/, filePath, strings.Split(fileheader.Filename, ".")[1] /*extension*/)
if err != nil {
cio.PrintMessage(1, err.Error())
return
}
bytesCopied, err := fsys.StoreImage(filePath, file)
if err != nil {
cio.PrintMessage(1, err.Error())
return
}
cio.PrintMessage(0, "File "+filePath+" has been created.")
if err != nil {
cio.PrintMessage(1, err.Error())
return
}
cio.PrintMessage(0, "Content of uploaded image ("+strconv.FormatInt(bytesCopied, 10)+" Bytes) has been copied to "+filePath+".")
http.Redirect(w, req, "/"+id, http.StatusFound)
}
}
Qt C ++客户端代码:
void Share::upload(const QByteArray &data) {
QHttpMultiPart *multi_part = new QHttpMultiPart(QHttpMultiPart::FormDataType);
QHttpPart text_part;
text_part.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"text\"\""));
text_part.setBody("Screenshot.png");
QHttpPart image_part;
image_part.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/png"));
image_part.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"image\""));
image_part.setBody(data);
multi_part->append(text_part);
multi_part->append(image_part);
QNetworkRequest request(QUrl("http://localhost:8000/api/upload"));
QNetworkAccessManager *manager = new QNetworkAccessManager();
connect(manager, SIGNAL(finished(QNetworkReply *)), this, SLOT(reply_finished(QNetworkReply *)));
manager->post(request, multi_part);
qDebug() << QString(data);
}
答案 0 :(得分:1)
我不确定但你可以尝试改变
image_part.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"image\""));
类似
image_part.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"image\"; filename=\"Screenshot.png\""));