【问题标题】:How to send files with superagent如何使用 superagent 发送文件
【发布时间】:2015-10-23 07:06:21
【问题描述】:

所以大约一个月前,我向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);
    })

谁能告诉我发生了什么事。

【问题讨论】:

    标签: ajax multipartform-data form-data superagent


    【解决方案1】:

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

    据此:

    当你使用 .field() 或 .attach() 时,你不能使用 .send() 并且你不能设置 Content-Type(会为你设置正确的类型)。

    此外,即使这里不是这种情况,也有许多帖子/问题中人们使用文件名作为.attach 的第二个参数。再次来自此文档页面:

    在浏览器中创建一个具有适当类型的 Blob。

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

    【讨论】:

      【解决方案2】:

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

      使用异步/等待

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

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

      【讨论】:

        【解决方案3】:

        附加应该可以工作。
        使用 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();
         });
        

        【讨论】:

        • 这就像一个魅力,multer在服务器端有很大帮助。
        • 对我来说,这很好用。在服务器上,我使用 async-busboy 来解析多格式数据。
        【解决方案4】:

        这应该可行。

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

        【讨论】:

        • attach 只能用于服务器端。你需要o指定文件的路径作为第二个参数,浏览器不能访问文件系统。
        • @CodrinIftimie,您的评论有误导性。 “附加”在前端工作得很好。我刚刚使用“附加”在我的一个项目中上传文件。理论实现在这里得到了很好的解释:abandon.ie/notebook/simple-file-uploads-using-jquery-ajax.
        • @bstst 这个线程是关于 superagent,而不是 jquery ajax。 superagent的“attach”方法只在nodejs中支持。
        • 我的错,我很困惑,因为链接与评论没有任何关系,直到昨天超级代理的附加+进度在浏览器中不起作用。为进步而欢呼:)
        • 另外需要注意的是:.attach 将文件作为多部分发送。这适用于网络服务器,但如果上传到 S3 或其他对象存储,您需要将文件发送为 .send(file)
        猜你喜欢
        • 2016-03-14
        • 2017-12-04
        • 1970-01-01
        • 2015-08-24
        • 2014-07-17
        • 1970-01-01
        • 1970-01-01
        • 2020-05-16
        • 2014-02-03
        相关资源
        最近更新 更多