file-upload - 如何从 node.js 上传文件

标签 file-upload node.js

当我查询这个问题时,我发现了很多帖子,但它们都是指如何将文件从浏览器上传到 node.js 服务器。我想将 node.js 代码中的文件上传到另一台服务器。我试图根据我对node.js的有限知识编写它,但它不起作用。

function (data) {
  var reqdata = 'file='+data;
  var request = http.request({
    host : HOST_NAME,
    port : HOST_PORT,
    path : PATH,
    method : 'POST',
    headers : {
      'Content-Type' : 'multipart/form-data',
      'Content-Length' : reqdata.length
    }
  }, function (response) {
      var data = '';
      response.on('data', function(chunk) {
        data += chunk.toString();
      });
      response.on('end', function() {
        console.log(data);
      });
    });

  request.write(reqdata+'\r\n\r\n');
  request.end();
})

上述函数被其他生成数据的代码调用。

我尝试使用 curl -F "file=@"上传相同的数据文件并且上传成功。但是我的代码失败了。服务器返回一个特定于应用程序的错误,提示上传的文件无效/损坏。

我收集了 tcpdump 数据并在wireshark 中进行了分析。从我的 node.js 代码发送的数据包缺少多部分数据所需的边界。我在 Wireshark 数据包中看到这条消息

The multipart dissector could not find the required boundary parameter.

知道如何在 node.js 代码中实现这一点吗?

最佳答案

jhcc's answer快到了。

为了在我们的测试中提供对此的支持,我对其进行了微调。

这是适合我们的修改版本:

var boundaryKey = Math.random().toString(16); // random string
request.setHeader('Content-Type', 'multipart/form-data; boundary="'+boundaryKey+'"');
// the header for the one and only part (need to use CRLF here)
request.write( 
  '--' + boundaryKey + '\r\n'
  // use your file's mime type here, if known
  + 'Content-Type: application/octet-stream\r\n' 
  // "name" is the name of the form field
  // "filename" is the name of the original file
  + 'Content-Disposition: form-data; name="my_file"; filename="my_file.bin"\r\n'
  + 'Content-Transfer-Encoding: binary\r\n\r\n' 
);
fs.createReadStream('./my_file.bin', { bufferSize: 4 * 1024 })
  .on('end', function() {
    // mark the end of the one and only part
    request.end('\r\n--' + boundaryKey + '--'); 
  })
  // set "end" to false in the options so .end() isn't called on the request
  .pipe(request, { end: false }) // maybe write directly to the socket here?

变化是:

  • ReadableStream.pipe returns the piped-to stream ,所以 end 永远不会被调用。相反,在文件读取流上等待 end
  • request.end 将边界换行。

关于file-upload - 如何从 node.js 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5744990/

相关文章:

javascript - Github高危js应用安全漏洞: GHSA-7fhm-mqm4-2wp7 with a Node.

asp.net - 如果 (fileUpload.HasFile)=false

powershell - 如何使用Invoke-RestMethod上传jpg

javascript - 如何在uploadcare中上传多个文件?

scala - Play 2.x : Reactive file upload with Iteratees

node.js - Node 集群有多个进程监听同一个端口

node.js - Sinon 函数 stub : How to call "own" function inside module

javascript - 显示具有在线编辑能力的文档

php - Javascript 和 PHP 上传系统

javascript - 第一次异常后继续测试 | Chai | Mocha