How to send files with superagent

前端 未结 4 847
南笙
南笙 2021-01-03 03:46

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 su

相关标签:
4条回答
  • 2021-01-03 04:22

    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();
     });
    
    0 讨论(0)
  • 2021-01-03 04:31

    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);
        })
    
    0 讨论(0)
  • 2021-01-03 04:39

    To complete previous answers and provide a reference, check this page: https://visionmedia.github.io/superagent/#multipart-requests

    According to it:

    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).

    Also, even if this is not the case here, there are many posts/questions where people use the filename as the second argument for .attach. Again from this doc page:

    In browser create a Blob with an appropriate type instead.

    This doesn't refer to the second argument, but to a third 'options' one, but to me it implies that filenames are not supported in the browser version.

    0 讨论(0)
  • 2021-01-03 04:47

    No one asked, but I think this might benefit a few.

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

    I have worked here the error module, you can process the response object the similar way for pass cases.

    0 讨论(0)
提交回复
热议问题