大家好,我在尝试在 express js 中使用 multer 存储从 html 表单获取的图像时出现错误



我正在制作一个小应用程序,我想在其中存储从类型文件的输入字段获得的图像,我遵循了multer文档的指南,但当我试图提交我的表单时,我得到了这个错误错误:enent:没有这样的文件或目录。

根据代码,图像应该从根目录

中挑选并存储在我的/images文件夹中。我的App.js文件

const multer = require('multer');
const fileStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, path.join(__dirname, 'images'));
},
filename: (req, file, cb) => {
cb(null, new Date().toISOString() + '-' + file.originalname);
} 
});
app.use(multer({storage: fileStorage}).single('image'));

my ejs view

<form class="product-form" action="/admin/add-product" method="POST" enctype="multipart/form-data">
<div class="form-control">
<label for="image">Image</label>
<input
type="file" 
name="image" 
id="image" 
>
</div>
<button class="btn" type="submit">Upload</button>
</form>

我package.js

{
"name": "full-recap",
"version": "1.0.0",
"description": "recap",
"main": "app.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1",
"start": "nodemon app.js"
},
"author": "",
"license": "ISC",
"devDependencies": {
"nodemon": "^2.0.20"
},
"dependencies": {
"@sendgrid/mail": "^7.7.0",
"bcryptjs": "^2.4.3",
"body-parser": "^1.20.1",
"connect-flash": "^0.1.1",
"connect-mongodb-session": "^3.1.1",
"csurf": "^1.11.0",
"dotenv": "^16.0.3",
"ejs": "^3.1.8",
"express": "^4.18.2",
"express-handlebars": "^6.0.6",
"express-session": "^1.17.3",
"express-validator": "^6.14.2",
"mongodb": "^4.12.1",
"mongoose": "^6.8.0",
"multer": "^1.4.5-lts.1"
}
}

和完整的错误我得到的是"错误:enent:没有这样的文件或目录,打开'C:UsersDunia DuniaDesktopCoding my careerNodejs full - recap images2023-01-05 t22:58:24 . 937z - firstpicture .jpg'">

嗯,我得到了别人的帮助,我能够解决这个问题。

上面的代码结构应该在MAC上工作,但在windows上有一个函数要添加到文件名定义

const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, path.join(__dirname, './images/'));
},
filename: (req, file, cb) => {
cb(null, new Date().toISOString().replace(/:/g, '-') + '-' + file.originalname);
}
});

toISOString()之后应该增加替换功能

最新更新