我使用node和express..uploading上传图片到gridfs-stream工作正常,但无法下载
app.post('/upload', function (req, res) {
var tempfile = req.files.displayImage.path;
var origname = req.files.displayImage.name;
var _id = guid();
var writestream = gfs.createWriteStream({
filename: _id
});
// open a stream to the temporary file created by Express...
fs.createReadStream(tempfile)
.on('end', function () {
res.send(_id);
})
.on('error', function () {
res.send('ERR');
})
// and pipe it to gfs
.pipe(writestream);
});
app.get('/download', function (req, res) {
// TODO: set proper mime type + filename, handle errors, etc...
gfs
// create a read stream from gfs...
.createReadStream({
filename: req.param('filename')
})
// and pipe it to Express' response
.pipe(res);
});
以上代码无法通过此cmd download?filename=acf58ae4-c853-f9f3-5c66-c395b663298a
答案 0 :(得分:0)
您可能需要检查params中的值。但希望这个 near 最小样本提供一些帮助:
它有帮助,因为它突出显示您正在查找_id
作为文件名。相反,你应该这样做:
.createReadStream({
_id: req.param('filename')
})
如果不是
.createReadStream({
_id: mongoose.Types.ObjectId(req.param('filename'))
})
由于_id
字段与文件名
<强> app.js 强>
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var app = express();
var mongoose = require('mongoose');
var Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo;
var conn = mongoose.createConnection('mongodb://localhost/mytest');
conn.once('open', function() {
console.log('opened connection');
gfs = Grid(conn.db);
// all environments
app.set('port', process.env.PORT || 3000);
app.use(express.logger('dev'));
app.use(app.router);
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
});
<强>路由/ index.js 强>
exports.index = function(req, res){
res.set('Content-Type', 'image/jpeg');
gfs.createReadStream({
filename: 'receptor.jpg'
}).pipe(res);
};