1

html form:

form(
    action="/profile/"+ user._id +"/user-img" 
    method="POST" enctype="multipart/form-data"
)
    input(type="file" name="img" required)
    input(type="submit" value="Load")

middleware file:

const multer = require('multer');
const storage = multer.diskStorage({
    destination(req, file, cb) {
        cb(null, 'upload');
    },
    filename(req, file, cb) {
        cb(null, new Date().toISOString() + '-' + file.originalname);
    }   
});

const allowedTypes = ['image/png', 'image/jpg', 'image/jpeg', 'image/gif'];

const fileFilter = (req, file, cb) => {
    if (allowedTypes.includes(file.mimetype)) {
        cb(null, true);
    } else {
        cb(null, false);
    }
}

module.exports = multer({
    storage, fileFilter
})

route:

router.post('/:id/user-img', async(req, res) => {
    try {
        const userFind = await User.findById(req.params.id);

        await User.updateOne({
            email: userFind.email
        },{$set: {
            img: req.file.path
        }})

        res.redirect('/profile/'+userFind._id);
    } catch (e) {
        console.log(e.message);
    }
})

server:

app.use(fileMiddleware.single('img'));

Error: ENOENT: no such file or directory, open...

Хотя папка upload у меня есть, но туда ничего не загружается, что не так?

1

1 ответ 1

1
filename(req, file, cb) {
  cb(null, new Date().toISOString() + '-' + file.originalname);
}

Двоеточия ":" не допускаются в именах файлов в операционной системе Windows.

Так что, нужно после new Date().toISOString() добавить вызов replace(), в котором заменить ":" любым допустимым символом.

Например:

new Date().toISOString().replace(/:/g, '-')

Свободный перевод ответа участника Miles на вопрос ENOENT: no such file or directory .?

1

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.