如何用C++通过HTTP协议上传文件



我要用C++将文件上传到Java春季启动web服务器。

我构建的协议如下(纯文本(:

POST /gallery/multimedia/uploadvideo HTTP/1.1
Host: 192.168.0.133:8981
Content-Type: multipart/form-data; boundary=------boundary1804289383
Connection: keep-alive
--------boundary1804289383
Content-Type: video/mp4
Content-Disposition: form-data; name="file"; filename="1.mp4"
Content-Length: 948611
Content-Transfer-Encoding: 8bit
... binary video data here ...
--------boundary1804289383--

服务器端是Java spring引导服务器,接口定义如下:

@PostMapping("uploadvideo")
public ResultVo uploadVideo(@RequestParam("file") MultipartFile file);

当发布文件时,服务器用代码400进行响应,并抱怨

所需的请求部分"文件"不存在

然而,使用一个简单的HTML页面,文件上传成功,HTML页面如下所示:

<html>
<head></head>
<body>
<form id="form" enctype="multipart/form-data" method="post" 
action="http://192.168.0.133:8981/gallery/multimedia/uploadvideo">
<input id="file" name="file" type="file" />
<input id="submit" value="submit" type="submit" />
</form>
</body>
</html>

我想念什么?


编辑:

我试过Postman/Chrome-console/curl,所有这些工具只打印请求,看起来像:

# this is from curl
POST /gallery/multimedia/uploadvideo HTTP/1.1
User-Agent: curl/7.29.0
Host: 192.168.0.133:8981
Accept: */*
Content-Length: 187
Expect: 100-continue
Content-Type: multipart/form-data; boundary=----------------------------3c653d03b97f

我应该如何构造文件部分?有什么想法吗?

首先,感谢@strupo的建议。

通过打开curl--trace选项并查看输出日志文件,我终于解决了这个问题。

curl中,它通过几个数据包发布文件:

标题:

POST /gallery/multimedia/uploadvideo HTTP/1.1
User-Agent: curl/7.29.0
Host: 192.168.0.133:8981
Accept: */*
Content-Length: 13602  # you have to calculate content length first
Expect: 100-continue   # very important line
Content-Type: multipart/form-data; boundary=------3c653d03b97f

然后等待服务器响应:

HTTP/1.1 100

在服务器响应代码100后,它发送数据内容,表单数据头首先出现:

--------3c653d03b97f
Content-Type: video/mp4
Content-Disposition: form-data; name="file"; filename="1.mp4"
Content-Length: 6640
Content-Transfer-Encoding: 8bit

文件内容如下(在我的情况下,分配了一个大内存,从文件中读取并写入套接字一次(,然后是下一个文件。

最后,协议应该以边界线结束:

--------3c653d03b97f--

Content-Length应包括在标头之后发送的所有字节。在文件部分,boundary应以--为前缀。此外,还应注意无处不在的rn

最新更新