【发布时间】:2021-03-08 09:30:19
【问题描述】:
我正在尝试使用 Postman 将图像上传到我的目录。我正在使用 Nodejs 和 multer 作为中间件。
我的问题如下,为什么我的代码给出了双\\,我该怎么做才能将路径名中的双反斜杠改为正斜杠?
到目前为止我的代码是:
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 错误