如何使用 superagent 发送文件

How to send files with superagent

大约一个月前,我询问了 a question 关于超级代理和发送文件的问题,但没有得到任何回应。我仍然想了解如何执行此操作,因为我喜欢使用 superagent。

我可以使用纯格式发送文件 ajax:

var fd = new FormData();
        fd.append( 'file', this.refs.File.getDOMNode().files[0] );

        $.ajax({
            url: 'http://localhost:8080/files',
            data: fd,
            processData: false,
            contentType: false,
            type: 'POST',
            success: function(data){
                console.log(data)
            }
        });

但是当我在 superagent 中尝试同样的事情时,没有任何效果:

var fd = new FormData();
fd.append( 'file', this.refs.File.getDOMNode().files[0] );

Request.post('http://localhost:8080/files')
    .set('Content-Type', false)
    .set('Process-Data', false)
    .attach('file', fd, 'file')
    .end((err, res) => {
        console.log(err);
        console.log(res);
    })

谁能告诉我这是怎么回事。

这应该有效。

var file = this.refs.File.getDOMNode().files[0];


Request.post('http://localhost:8080/files')
    .set("Content-Type", "application/octet-stream")
    .send(file)
    .end((err, res) => {
        console.log(err);
        console.log(res);
    })

附加应该工作。
使用 express/multer 的示例:

客户:

superagent.post('http://localhost:3700/upload').attach('theFile',file);

服务器:

 const storage = multer.memoryStorage();
 const upload = multer({ storage: storage });
 router.post("/upload", upload.single('theFile'), (req, res) => {
   debug(req.file.buffer);
   res.status(200).send( true );
   res.end();
 });

没有人问,但我认为这可能会使一些人受益。

使用async/await

describe('My App - Upload Module', function(){
  it('Upload Module - ERROR - upload an expired file', async function(){
    try{
      let res = await _upload_license_file("/tmp/test_license.xml");
    }catch(err){
      err.should.have.status(422);
    }
  });
});

async function _upload_license_file(fileLocation){
  return superAgent.post(base_url + "/upload")
          .set('Authorization', 'Bearer '+API_TOKEN)
          .set('Content-Type', 'multipart/form-data')
          .attach('xml_file', fileLocation)
}

我在这里工作过错误模块,你可以用类似的方式处理通过案例的响应对象。

要完成以前的答案并提供参考,请查看此页面: https://visionmedia.github.io/superagent/#multipart-requests

据此:

When you use .field() or .attach() you can't use .send() and you must not set Content-Type (the correct type will be set for you).

此外,即使这里不是这种情况,也有很多 posts/questions 人们将文件名用作 .attach 的第二个参数。再次来自此文档页面:

In browser create a Blob with an appropriate type instead.

这不是指第二个参数,而是第三个 'options',但对我来说,这意味着浏览器版本不支持文件名。