文件下载不适用于Node.js gridfs

编程入门 行业动态 更新时间:2024-10-25 04:23:02
本文介绍了文件下载不适用于Node.js gridfs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用node和express将图像上传到gridfs-stream.上传工作正常,但无法下载

i'm uploading images to gridfs-stream using node and express..uploading is working fine but am unable to download

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

the above code is unable to download the image by this cmd download?filename=acf58ae4-c853-f9f3-5c66-c395b663298a

推荐答案

您可能需要检查参数中的值.但是希望这个 near 最小样本可以提供一些帮助:

You might need to check your values in params. But hopefully this near minimal sample provides some help:

它有所帮助,因为它突出显示您正在将_id查找为文件名.相反,您应该这样做:

And it has helped, because it highlights that you are looking up the _id as a filename. Instead you should be doing this:

.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')); }); });

routes/index.js

exports.index = function(req, res){ res.set('Content-Type', 'image/jpeg'); gfs.createReadStream({ filename: 'receptor.jpg' }).pipe(res); };

更多推荐

文件下载不适用于Node.js gridfs

本文发布于:2023-11-28 19:44:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643712.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不适用于   文件   Node   js   gridfs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!