文件下载不适用于Node.js gridfs [英] File download is not working with nodejs gridfs

查看:131
本文介绍了文件下载不适用于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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆