Nodejs express multer 文件上传+路径包含双斜线

Nodejs express multer file upload + path contains double slashes

我正在尝试使用 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);
  },
});

我也试过在 Whosebug 上搜索类似的帖子,例如尝试这个帖子回答

您可以使用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);
  },
});

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

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

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

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

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

Original answer here