【问题标题】:Nodejs express multer file upload + path contains double slashesNodejs express multer文件上传+路径包含双斜杠
【发布时间】:2021-03-08 09:30:19
【问题描述】:

我正在尝试使用 Postman 将图像上传到我的目录。我正在使用 Nodejs 和 multer 作为中间件。

但是,我收到一个 ENOENT 错误:

我的问题如下,为什么我的代码给出了双\\,我该怎么做才能将路径名中的双反斜杠改为正斜杠?

到目前为止我的代码是:

const multer = require('multer');

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '.test/');
  },
  filename: function (req, file, cb) {
    cb(null, new Date().toISOString() + file.originalname);
  },
});
router.post('/', upload.single('productImage'), (req, res, next) => {
  console.log(req.file);
...
...
...

我尝试过使用 .replace() 方法,但没有成功。

const multer = require('multer');

let destination = '.uploads/';

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, destination.replace('\\','/'));
  },
  filename: function (req, file, cb) {
    cb(null, new Date().toISOString() + file.originalname);
  },
});

我也试过在 StackOverflow 上搜索类似的帖子,例如尝试这个帖子回答 Error: ENOENT: no such file or directory,

【问题讨论】:

  • .test/ 不是有效路径。您应该使用path 模块和反引号(“`”)来连接字符串(路径)
  • 你替换只会替换一个实例,试试 cb(null, destination.replace(/\\\\/g, '/'));替换所有实例。
  • 仍然 ENOENT 错误

标签: node.js multer


【解决方案1】:

您可以使用path.normalize('\\dsgsd\\sdgsdg') 方法。你可以在 NodeJS 官方文档中找到它https://nodejs.org/api/path.html#path_path_normalize_path

const multer = require('multer');
const { normalize } = require('path')

let destination = '.uploads/';

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, normalize(destination));
  },
  filename: function (req, file, cb) {
    cb(null, new Date().toISOString() + file.originalname);
  },
});

【讨论】:

  • 是的,我使用的是 macOS。如果使用 macOS,则必须像 Unix 系统一样更改路径。
  • @haycon 你试过let destination = path.join(__dirname, '/uploads/'); 吗??
  • 是的,那没有用。但是,我找到了答案,如果您对它是如何完成的感到好奇,请阅读我的其他答案。
【解决方案2】:

经过一番谷歌搜索,我找到了答案。

问题不在于双 \\,它们是允许的,问题在于文件名的保存方式。文件名是日期字符串,保存格式为:2020-11-25T12:15something,问题是Windows操作系统不接受带有字符“:”的文件。

解决方案是替换这行代码:

cb(null, new Date().toISOString() + file.originalname);

cb(null, new Date().toISOString().replace(/:/g, '-') + file.originalname);

Original answer here

【讨论】:

    猜你喜欢
    • 2017-09-29
    • 2021-12-27
    • 1970-01-01
    • 2018-07-21
    • 2019-07-13
    • 1970-01-01
    • 2020-11-20
    • 2013-07-23
    • 1970-01-01
    相关资源
    最近更新 更多