博客列表 >如何用nodeJs向别的服务器上传文件发送formData数据?

如何用nodeJs向别的服务器上传文件发送formData数据?

子龙的博客搬家啦httpswwwcnblogscomZiLongZiLong
子龙的博客搬家啦httpswwwcnblogscomZiLongZiLong原创
2021年04月27日 17:36:353556浏览

最近,接手到一个项目,在测试阶段需要频繁的打包 -> 上传 -> 新建 -> … -> … 于是想着能不能将这些重复无脑的工作使用代码简化了,于是便有了文章标题名字的问题.

要想完成这个工作首先要有个可以发起的http请求的工具,这里我是使用了http(s).request这个方法,他会为我们创建一个http.ClientRequest类的对象 我们基于这个对象可以完成一次http请求的发送和响应的接收。
eg:

  1. const options = {
  2. hostname:'host',
  3. port: 443,
  4. path:'path',
  5. method: 'method',
  6. headers:{
  7. }
  8. }
  9. const hcr = http.request(options,(res) => {
  10. // 这里接收响应
  11. let chunks = Buffer.from([]);
  12. res.on('data', chunk => {
  13. chunks = Buffer.concat([chunks,chunk])
  14. });
  15. res.on('end',() =>{
  16. const res = JSON.parse(chunks.toString('utf-8'));
  17. console.log(res,'就是我们接收到的响应')
  18. })
  19. })
  20. hcr.end('要发送的数据')

基本上一个普通的http post请求在设置好请求头后在end里直接将键值对数据JSON stringify了发送就行,但是在发送文件的时候,有个东西我们必须得知到就是发送文件的数据格式,以chrmome举例,在一个请求头为Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryGe1u5fl4IETGv48y的传输中,数据格式是这样的:

  1. ------WebKitFormBoundaryGe1u5fl4IETGv48y
  2. Content-Disposition: form-data; name="type"
  3. H5
  4. ------WebKitFormBoundaryGe1u5fl4IETGv48y
  5. Content-Disposition: form-data; name="file"; filename="package1.0.161.zip"
  6. Content-Type: application/x-zip-compressed
  7. 这里就是二进制数据了
  8. ------WebKitFormBoundaryGe1u5fl4IETGv48y--

这个格式就是以boundary作为开始结束和字段之间的间隔,中间有一些请求头和真实数据,并且以换行符(\r\n)分割,请求头所在行的name就是服务端接收这个字段的key,所以我们照着拼好这个格式就可以搞定传输了:

  1. let chunks = Buffer.from([]);
  2. let endBuffer = ([
  3. Buffer.from(`--${boundaryKey}\r\n`),
  4. Buffer.from(`Content-Disposition: form-data; name="type"\r\n`),
  5. Buffer.from(`\r\n`),
  6. Buffer.from(`H5\r\n`),
  7. Buffer.from(`--${boundaryKey}\r\n`),
  8. Buffer.from(`Content-Disposition: form-data; name="file"; filename="${'文件名'}\r\n`),
  9. Buffer.from(`Content-Type: application/x-zip-compressed\r\n`),
  10. Buffer.from(`\r\n`),
  11. fs.readFileSync(`你的文件路径`),
  12. Buffer.from(`\r\n`),
  13. Buffer.from(`--${boundaryKey}--`)
  14. ])
  15. endBuffer.forEach( buf => {
  16. chunks = Buffer.concat([chunks,buf])
  17. })

拼好这个chunks,配置好options请求头的Content-Type然后使用end方法将其发送就ok了。

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议