0

我正在将文件(多部分/表单数据)上传到 Koa,并希望将其存储到 RethinkDB 中。

我用 co-busboy 解析它,这会产生一个流。

然后我通过将数据/结束侦听器附加到它,收集所有缓冲区并将它们连接起来,将流转换为缓冲区。

完成此操作后,我得到我的数据库记录,将缓冲区放入正确的字段并保存。

但我总是收到范围错误,因此永远不会保存更新。

我创建的缓冲区是否需要一些额外的信息让 RethinkDB 存储它?

4

1 回答 1

1

您不需要任何其他信息来存储它。以 koajs https://github.com/koajs/examples/blob/master/multipart/app.js的直接示例,使用您所描述的,这是适用于我的代码。

var os = require('os');
var path = require('path');
var koa = require('koa');
var fs = require('co-fs');
var parse = require('co-busboy');
var saveTo = require('save-to');
var app = module.exports = koa();
var r = require('rethinkdb')


r.connect()
  .then(function(conn) {
    app.use(function *(){
      // parse the multipart body
      var parts = parse(this, {
        autoFields: true // saves the fields to parts.field(s)
      });

      // create a temporary folder to store files
      var tmpdir = path.join(os.tmpdir(), uid());

      // make the temporary directory
      yield fs.mkdir(tmpdir);

      // list of all the files
      var files = [];
      var file;

      // yield each part as a stream
      var bufs = [];
      var part;
      while (part = yield parts) {
        // filename for this part
        files.push(file = path.join(tmpdir, part.filename));
        // save the file
        // yield saveTo(part, file);
        // We are saving into RethinkDB
        part.on('data', function(d){ bufs.push(d); });
        part.on('end', function(){
          var buf = Buffer.concat(bufs);

          r.table('user').insert({
            file: buf
          })
          .run(conn)
          .then(function(cursor) {
            console.log(cursor)
          })

        })
      }


      // return all the filenames as an array
      // after all the files have finished downloading
      this.body = files;

    })

})


if (!module.parent) app.listen(3000);

function uid() {
  return Math.random().toString(36).slice(2);
}

然后发送请求:

curl -F "file=@./a.png" 127.0.0.1:3000

应该使用二进制数据插入一个新文档

于 2015-12-30T18:58:44.243 回答