How to send files with superagent

你。 提交于 2019-11-30 18:11:00

问题


So about a month ago I asked a question regarding superagent and sending files, but got no response at all. I would still like to find out how to do this as I enjoy using superagent.

I am able to send files using plain 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)
            }
        });

But when I try the same thing in superagent, nothing works:

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);
    })

Can anyone, please, tell me whats going on.


回答1:


This should work.

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);
    })



回答2:


Attach should work.
Example using express/multer:

client:

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

server:

 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();
 });


来源:https://stackoverflow.com/questions/31748936/how-to-send-files-with-superagent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!