如何使用 knex 插入 blob?

How to insert blob using knex?

目前,我有一个使用 ng-file-upload 到另一台服务器的上传系统,由于 CORS,它运行良好。

为了管理我的数据库,我使用 knex(迁移和种子),并且我有一个特定的 table 和一个 bytea 列。

PostgreSQL 数据库。

为了使上传成为可能,我添加了 busboy 模块以允许 express 管理多部分请求,并且文件正在毫无问题地保存到磁盘。

但我真正想要的是将它保存在 bytea 列中的 table 中,而现在我在这样的任务中没有运气。

欢迎提供任何指导和更好的文档。

最好的方法是使用 Amazon s3 或其他服务来存储 blob,同时将元数据存储在 sql。

如果你想存储,你可以使用sql驱动程序和bluebird。

想了很久才明白。

最终使上传与 angular+express+knex+postgres

一起工作非常简单

首先,没有必要打杂,相反,你需要 bodyParser's raw mode

其次,将其调整为合理的上传大小。

第三,ng-file-upload会帮忙上传部分

如果有人需要,这里有一些片段:

上传按钮:

<div layout="row" layout-align="center center">
  <md-button ngf-select ng-model="arquivo" class="md-raised md-primary">Selecionar arquivo</md-button>
  <md-button ng-show="arquivo" ng-click="arquivo = null" class="md-raised md-warn">Cancelar</md-button>
  <md-button ng-show="arquivo" ng-click="sendarquivo(arquivo)" class="md-raised md-primary" ng-disabled="arquivo.size > 4096 * 1024">Enviar arquivo</md-button>
</div>

controller.sendarquivo:

$scope.sendarquivo = function (arquivo) {
  enqueteservice.uploadanexo(idenquete, arquivo).then(function () {
    $scope.list();
    $scope.arquivo = null;
  });
};

enqueteservice.uploadanexo:

// serviço de enquete
angular.module("roundabout").factory("enqueteservice", function($http, Upload) {
  return {
    uploadanexo: function(idenquete, file) {
      return Upload.http({
        url: "/enquete/" + idenquete + "/uploadanexo/" + file.name,
        method: 'POST',
        headers: {
          'Content-Type': 'application/octet-stream' // file.type //  
        },
        data: file
      });
    }
  }
});

在服务器端,快速路由器:

router.post("/:idenquete/uploadanexo/:descricaoanexoenquete", function (req, res) {
  knex("anexoenquete").insert({
    idenquete: req.params.idenquete,
    descricaoanexoenquete: req.params.descricaoanexoenquete,
    dadoanexoenquete: req.body
  }, "idanexoenquete").then(function (ret) {
    res.send("idanexoenquete:" + ret[0]);
  }).catch(function (err) {
    res.status(500).send(err);
    console.log(err);
  });
});

作为参考,bodyParser 设置在 index.js

// ...
app.use(bodyParser.json({limit: 1024 * 1024}));// 1MB of json is a lot of json
// parse some custom thing into a Buffer
app.use(bodyParser.raw({limit: 10240 * 1024, type: 'application/octet-stream'})); // 10 MB of attachments

使用此设置,ng-file-upload 主体将作为 Buffer 到达快速路由器,您可以直接传递给 knex 插入语句。

下载二进制内容也可以轻松解决如下:

下载附件

router.get("/downloadanexo/:idanexoenquete", function (req, res) {
  knex("anexoenquete").select().where({
    idanexoenquete: req.params.idanexoenquete
  }).then(function (ret) {
    if (!ret.length)
      res.status(404).send("NOT FOUND");
    else {
      var anexoenquete = ret[0];
      res.setHeader("Content-disposition", "attachment;filename=" + anexoenquete.descricaoanexoenquete);
      res.send(anexoenquete.dadoanexoenquete);
    }
  }).catch(function (err) {
    res.status(500).send(err);
    console.log(err);
  });
});

希望此参考资料对以后的其他人有所帮助,我可以关闭一个简单的 java 应用程序,它为我解决了这个问题。