如何用superagent发送文件

Jul*_*ent 3 ajax multipartform-data form-data superagent

所以大约一个月前我问了一个关于superagent和发送文件的问题,但根本没有回复.我仍然想知道如何做到这一点,因为我喜欢使用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)
            }
        });
Run Code Online (Sandbox Code Playgroud)

但是当我在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);
    })
Run Code Online (Sandbox Code Playgroud)

任何人,请告诉我发生了什么事.

Hos*_*sar 11

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

客户:

superagent.post('http://localhost:3700/upload').attach('theFile',file);
Run Code Online (Sandbox Code Playgroud)

服务器:

 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();
 });
Run Code Online (Sandbox Code Playgroud)


小智 5

这应该工作.

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);
    })
Run Code Online (Sandbox Code Playgroud)

  • @CodrinIftimie,你的评论是误导."附加"在前端完美运行.我刚刚在我的一个项目中使用"附加"来上传文件.理论实现在这里得到了很好的解释:http://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax. (3认同)
  • 需要注意的另一件事:.attach将文件作为多部分发送。这适用于Web服务器,但是如果上传到S3或其他对象存储,则需要将文件发送为`.send(file)`。 (2认同)