【问题标题】:Meteor - What's the best way to get files from a post request?Meteor - 从发布请求中获取文件的最佳方式是什么?
【发布时间】:2015-01-10 03:48:21
【问题描述】:

我目前正在使用所见即所得的编辑器,它有一个image upload implementation,它向给定的 url 发送一个 post 请求,然后期望返回一些 JSON,如:{ "filelink": "/static/img.jpg" }显示上传的图片。

我目前的方法是创建一个服务器端路由,它会从请求正文中获取图像,将其发送到 s3,保存元数据(collectionFS),然后通过响应返回必要的 JSON。

我已经像这样实例化了编辑器:

Template.editor.rendered = function() {
  $("#editor").redactor({
  imageUpload: "s3"
  });
};

而服务器端的路由器是这样的:

Router.route('/s3', function () {
  this.response.setHeader("Content-Type", "text/html");
  var data = JSON.stringify(this.request.body;
  var res = this.response;
  res.end(data);
  }, {where: 'server'}
);

不幸的是,这会返回一个空白 JSON 对象。我尝试过 request.files 和 request.body.files,但这些都不起作用。

我知道路由是有效的,因为我可以通过响应发送纯 html。而且,我绝对可以在 firebug 的 post 请求中看到上传文件的二进制数据,但我似乎无法让 Meteor 获取这些文件。

【问题讨论】:

    标签: javascript meteor redactor


    【解决方案1】:

    调用中间件时 POST 数据不可用,而是在 data 事件中接收。您需要处理这些事件以获取文件数据。示例:

    Router.route('...', function() {
      var buffers = [];
      var totalLength = 0;
    
      this.request.on('error', function(err) {
        // handle network error here
      });
    
      this.request.on('data', function(chunk) {
        buffers.push(chunk);
        totalLength += chunk.length;
        if(totalLength > SOME_LARGE_CONSTANT) {
          // handle data overflow here
        }
      });
    
      this.request.on('end', function() {
        var data = Buffer.concat(buffers);
        // handle properly received data here
      });
    
    });
    

    【讨论】:

    • 我正在使用collectionFS创建一个文件对象,然后我将data附加到它,然后我将它上传到本地文件夹。由于某种原因,上传到该文件夹​​的任何图像都已损坏。文档提到attachData 应该能够毫无问题地在服务器上获取缓冲区或 ArrayBuffers。有什么建议吗?
    猜你喜欢
    • 1970-01-01
    • 2017-04-12
    • 2010-10-06
    • 2014-07-27
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多