【问题标题】:how to change a file originalname in Multer如何在 Multer 中更改文件的原始名称
【发布时间】:2021-06-03 10:00:56
【问题描述】:

我正在尝试将文件上传到 Google Cloud Storage 存储桶和 MongoDB,这实际上是有效的,但更改文件名并不是因为我不能,我已经在网上查找了它,但看不到类似的代码我的那么我如何更改文件originalname 添加date.now() 到它。

我的代码

const multer = Multer({
    storage: Multer.memoryStorage(),
    limits: {
      fileSize: 5 * 1024 * 1024, // no larger than 5mb, you can change as needed.
    },
  
  });
  

//CREATE FEED

Router.post('/', multer.array('files'), authoriazation, async (req, res) => {

    const { txt, Feedtype } = req.body
    const text = htmlToText(txt, {
        wordwrap: 130
      });
     
    // uploading multiple image
  
       
        const creteFeed = await new Feed({
            feedby: req.user,
            feedTxt: text,
            deleted: 0,
            feedReaction: 0,
            feedComment: 0,
            feedShare: 0,
            feedType: Feedtype,
        })
        const newFeed = await creteFeed.save()
  if (req.files.length > 0) {
        for (newfile of req.files) {
            const blob = bucket.file(newfile.originalname);
            const blobStream = blob.createWriteStream();
            if (newFeed) {
                const FeedMed = await new FeedMedia({
                    feed_id: newFeed._id,
                    feedby: req.user,
                    feedMedia_type: newfile.mimetype,
                    feedMedia_name: newfile.originalname,
                    category: 'feed',
                    url: `https://storage.googleapis.com/${bucket.name}/${newfile.originalname}`,
                    deleted: 0
                })
                const newFeedMed = await FeedMed.save()

                }

            blobStream.on('finish', async() => { 
            });

            blobStream.end(newfile.buffer);

        }

    }
    res.json('success')
})


【问题讨论】:

  • bucket文件名是否有originalName作为名字?除了originalName之外,您是否只想将日期附加到文件名?
  • 为什么不能只在 DB 中存储 originalname 并生成唯一的文件名以存储在 GCS 中?
  • 是的,我想将日期附加到文件名而不是原始名称,然后将其保存到数据库中

标签: node.js mongodb google-cloud-storage


【解决方案1】:

如果您想将 Date.now() 添加到 SERVER SIDE 中的 file.originalname 中,您可以这样做:

const multer = require('multer');
const storage = multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, 'www/img/');
  },
  filename: function (req, file, callback) {
    callback(null, Date.now() + '_' + file.originalname); // <-- CHANGE HERE
  }
})
const upload = multer({ storage: storage });

app.post("/upload", upload.single('file'), (req, res) => {
  res.status(200).send();
})

并制作一个 Fetch 帖子:

const file = document.querySelector("input#file").files[0];
const formData = new FormData()
formData.append('file', file); // <-- DO NOT CHANGE HERE

fetch('/upload', {
  method: 'POST',
  body: formData
});

但是,如果您想在 CLIENT SIDE 中将 Date.now() 添加到 file.originalname你可以这样做:

const multer = require('multer');
const storage = multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, 'www/img/');
  },
  filename: function (req, file, callback) {
    callback(null, file.originalname); // <-- DO NOT CHANGE HERE
  }
})
const upload = multer({ storage: storage });

app.post("/upload", upload.single('file'), (req, res) => {
  res.status(200).send();
})

并制作一个 Fetch 帖子:

const file = document.querySelector("input#file").files[0];
const formData = new FormData()
formData.append('file', file, Date.now() + '_' file.name); // <-- CHANGE HERE

fetch('/upload', {
  method: 'POST',
  body: formData
});

在这种情况下,file.originalname 将在发布后在 SERVER SIDE 中更改。

【讨论】:

    【解决方案2】:

    您正在使用不支持文件名选项的Multer.memoryStorage,因为在内存中存储文件时没有文件名。

    https://github.com/expressjs/multer/issues/288

    您可以改用Multer.diskStorage

    https://www.npmjs.com/package/multer#diskstorage

    var storage = multer.diskStorage({
      destination: function (req, file, cb) {
        cb(null, '/tmp/my-uploads')
      },
      filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now())
      }
    })
     
    var upload = multer({ storage: storage })
    

    【讨论】:

      猜你喜欢
      • 2020-06-20
      • 2021-03-29
      • 1970-01-01
      • 2021-02-04
      • 1970-01-01
      • 2017-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多