【问题标题】:Multer gridfs StorageMulter gridfs 存储
【发布时间】:2019-04-27 14:30:53
【问题描述】:

我想更改我的文件名,但是当我检查 console.log (req.file) 时,我可以看到我更改为的文件名,但使用 Multergridfs Storage 将不同的文件名保存在数据库中。

 1. the default filename 
 const storage = new GridFsStorage({
    url: config.db,
    file: (req, file) => {
        return new Promise((resolve, reject) => {
            crypto.randomBytes(16, (err, buf) => {
                if (err) {
                    return reject(err)
                }
                const filename = 'file' + path.extname(file.originalname);
                const fileInfo = {
                    filename: filename,
                    bucketName: 'contents'
                };
                resolve(fileInfo);
            });
        });
    }});

2 this is where i edited the filename

router.post('/', upload.single('file'), (req, res) => {
    req.file.filename = req.body.fileName + path.extname(req.file.originalname)
    res.redirect('/upload/files')
    
    console.log(req.file)
});

控制台的结果类似于

{ 字段名:'文件', originalname: '\'你也可以很棒\' - Elon Musk Motivation - Motivational Video.mp4', 编码:'7bit', mimetype: '视频/mp4', 编号:5bfb292c13eec142f6c20fd9, 文件名:'a.mp4', 元数据:空, 桶名:'内容', 块大小:261120, 尺寸:19372377, md5: '513c6220ef3afff644cf8a6dc4cd9130', 上传日期:2018-11-25T22:58:52.625Z, 内容类型:“视频/mp4”} { 文件名:'a' }

【问题讨论】:

  • 欢迎来到 Stackoverflow。请将您要显示的任何代码复制并粘贴到问题中。最好不要将嵌入图像用于代码或错误消息。

标签: node.js mongodb mongoose multer multer-gridfs-storage


【解决方案1】:

代码中的这部分

const storage = new GridFsStorage({
    url: config.db,
    file: (req, file) => { // In this function is where you configure the name of your file

file 配置是在将文件插入数据库之前计算文件名的配置。你正在做的是:

  1. 生成像'file' 这样的名称以及来自浏览器的任何扩展名,例如:'file.mp4'
  2. 将具有该名称的文件保存到数据库中
  3. 用新名称覆盖请求中的属性
  4. 数据库中的文件保持不变

我认为您真正想要的是生成正确的名称在插入之前

你可以使用

const storage = new GridFsStorage({
    url: config.db,
    file: (req, file) => {
        return new Promise((resolve, reject) => {
            crypto.randomBytes(16, (err, buf) => {
                if (err) {
                    return reject(err)
                }
                // In here you have access to the request and also to the body object
                const filename = req.body.fileName + path.extname(file.originalname);
                const fileInfo = {
                    filename: filename,
                    bucketName: 'contents'
                };
                resolve(fileInfo);
            });
        });
    }});

确保您在浏览器中的表单中发送文件之前的所有字段,否则某些值将是 undefined,因为它们尚未处理。

【讨论】:

  • file 对象或 files 数组是纯 JavaScript 对象。您可以直接在它们上设置新属性。此解决方案是否适合您?
  • @SadiqMustaphaAji 或者,您可以从它们创建自己的对象并直接操作它们
  • 请您提供有关如何创建对象的示例。 @devconcept
  • @SadiqMustaphaAji 首先,您是否知道更改这些属性对您的数据库结构没有影响。您是否打算将这些字段保留在数据库中?
  • 是的@devconcept
猜你喜欢
  • 2021-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-11
  • 2016-08-24
  • 2012-02-06
相关资源
最近更新 更多