首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Multer gridfs存储

Multer gridfs存储
EN

Stack Overflow用户
提问于 2018-11-25 22:44:08
回答 1查看 3.1K关注 0票数 0

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

代码语言:javascript
复制
 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)
});

控制台的结果类似于

{字段名:'file',原名:‘\’您也可以是伟大的\\‘- Elon Musk动机-励志视频.mp4’,编码:'7bit',mimetype:‘视频/MP4’,id: 5bfb29c13eec142f6c20fd9,文件名:'a.mp4',元数据: null,bucketName:'contents',chunkSize: 261120,大小: 19372377,md5:‘513c6220eff644cf8a6dc4cd9130,uploadDate: 2018-11-25T22:58:52.625Z,contentType:‘视频/MP4’}{ fileName:'a‘}

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-27 15:37:01

代码中的这一部分

代码语言:javascript
复制
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. 数据库中的文件保持不变。

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

您可以通过使用

代码语言:javascript
复制
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,因为它们尚未处理。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53472754

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档