Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send files with superagent

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.

like image 775
Julien Vincent Avatar asked Jul 31 '15 14:07

Julien Vincent


People also ask

How does a SuperAgent work?

A SuperAgent is a distributed repository which is designed to reduce the load on McAfee ePO. McAfee ePO manages how the SuperAgent is replicated. The SuperAgent caches information received from McAfee ePO, the Master Repository, an HTTP, or an FTP repository, and distributes it to the agents in its broadcast domain.

How do you set a SuperAgent header?

Here is a basic code: const superagent = require('superagent'); superagent. get('https://api.arabam.com/pp/step') . query({ apikey: '_V85Kref7xGZHc1XRpUmOhDDd07zhZTOvUSIbJe_sSNHSDV79EjODA==' }) .


2 Answers

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();
 });
like image 147
Hosar Avatar answered Nov 15 '22 02:11

Hosar


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);
    })
like image 30
Codrin Iftimie Avatar answered Nov 15 '22 02:11

Codrin Iftimie