繁体   English   中英

如何下载而不是流式传输我使用 node.js、express、mongodb 和 GridFSBucket 上传到 MongoDb 的文件?

[英]How to download and not stream files that i uploaded into MongoDb with node.js, express, mongodb and GridFSBucket?

上传下载功能

我上传文件和下载文件的功能是这样的。 uploadFiles 函数可以完美运行并完成它应该做的事情。

下载不符合我的要求。 它加载图像并流式传输它们。 我想要的是,它将文件从数据库下载到设备。 GridFSBucket 有没有可能做到这一点,还是我需要别的东西?

const uploadFiles = async(req, res) => {
            try {
                await upload(req, res);
                console.log(req.file);
                if (req.file == undefined) {
                    return res.send({
                        message: "You must select a file.",
                    });
                }
                return res.send({
                    message: "File has been uploaded.",
                });
            } catch (error) {
                console.log(error);
                return res.send({
                    message: "Error when trying upload image: ${error}",
                });
            }
        };
        
        const download = async(req, res) => {
            try {
                await mongoClient.connect();
                const database = mongoClient.db(dbConfig.database);
                const bucket = new GridFSBucket(database, {
                    bucketName: dbConfig.imgBucket,
                });
        
        
                let downloadStream = bucket.openDownloadStreamByName(req.params.name)
                downloadStream.pipe(fs.createWriteStream('./' + req.params.name)).
                on('error', function(error) {
                    console.log("error" + error);
                    res.status(404).json({
                        msg: error.message
                    });
                }).
                on('finish', function() {
                    console.log('done!');
                    res.send('Downloaded successfully!')
                });
                downloadStream.on("data", function(data) {
                    return res.status(200).write(data);
                });
                downloadStream.on("error", function(err) {
                    return res.status(404).send({ message: "Cannot download the Image!" });
                });
                downloadStream.on("end", () => {
                    return res.end();
                });
            } catch (error) {
                return res.status(500).send({
                    message: error.message,
                });
            }
        };

用于上传和存储图像的中间件

const util = require("util");
const multer = require("multer");
const { GridFsStorage } = require("multer-gridfs-storage");
const dbConfig = require("../config/db.config");


var storage = new GridFsStorage({
    url: dbConfig.url,
    options: { useNewUrlParser: true, useUnifiedTopology: true },
    file: (req, file) => {
        const match = ["image/png", "image/jpeg"];
        if (match.indexOf(file.mimetype) === -1) {
            const filename = `${Date.now()}-wolpert-${file.originalname}`;
            return filename;
        }
        return {
            bucketName: dbConfig.imgBucket,
            filename: `${Date.now()}-wolpert-${file.originalname}`
        };
    }
});
var uploadFiles = multer({ storage: storage }).single("file");
var uploadFilesMiddleware = util.promisify(uploadFiles);
module.exports = uploadFilesMiddleware;

路线

const express = require("express");
const router = express.Router();

const uploadController = require("../controller/upload");

const fileRoutes = express.Router({ mergeParams: true });

fileRoutes.route('/upload')
    .post(async(req, res) => {
        await uploadController.uploadFiles(req, res);
    });

fileRoutes.route('/files/:name')
    .get(async(req, res) => {
        await uploadController.download(req, res);
    });

下载意味着在设置指示浏览器下载文件的Content-Disposition标头(而不是内联显示)之后,将文件流式传输到 HTTP 响应。

try {
  await mongoClient.connect();
  const database = mongoClient.db(dbConfig.database);
  const bucket = new GridFSBucket(database, {
    bucketName: dbConfig.imgBucket,
  });
  let downloadStream = bucket.openDownloadStreamByName(req.params.name);
  res.set("Content-Disposition", "attachment");
  downloadStream.pipe(res);
} catch(error) {...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM