目前,我有一个使用 ng-file-upload 到另一台服务器的上传系统,这要归功于 CORS。
为了管理我的数据库,我使用 knex(迁移和种子),并且我有一个带有 bytea 列的特定表。
PostgreSQL 数据库。
为了使上传成为可能,我添加了 busboy 模块以允许 express 管理多部分请求,并且文件正在毫无问题地保存到磁盘。
但我真正想要的是把它保存在表中,在 bytea 列中,现在我在这样的任务上没有运气。
欢迎任何指导和更好的文档。
目前,我有一个使用 ng-file-upload 到另一台服务器的上传系统,这要归功于 CORS。
为了管理我的数据库,我使用 knex(迁移和种子),并且我有一个带有 bytea 列的特定表。
PostgreSQL 数据库。
为了使上传成为可能,我添加了 busboy 模块以允许 express 管理多部分请求,并且文件正在毫无问题地保存到磁盘。
但我真正想要的是把它保存在表中,在 bytea 列中,现在我在这样的任务上没有运气。
欢迎任何指导和更好的文档。
很久之后,我想通了。
最后,使用 angular+express+knex+postgres 进行上传非常简单
首先,不需要 busboy,相反,你需要bodyParser 的原始模式
其次,将其调整为合理的上传大小。
第三,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>
控制器.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);
});
});
作为参考,index.js 中的 bodyParser 设置
// ...
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 body 将作为Buffer到达 express 路由器,您可以直接将其传递给 knex insert 语句。
下载二进制内容也可以轻松解决,如下:
下载附件
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 应用程序,它为我解决了这个问题。
最好的方法是使用 Amazon s3 或其他服务来存储 blob,同时将元数据存储在 sql 中。
如果你还是想存储,你可以使用 sql driver 和 bluebird。