나는 Multer를 실험 해 왔으며 Mongoose를 사용하여 MongoDB에 영화 문서를 저장하는 작업을하고있었습니다. 사용자가 하나의 입력 필드에 이미지를 제출하고 별도의 입력 필드에 비디오를 제출하게 한 후 multer의 upload.fields () 옵션을 사용하여 이러한 파일을 처리합니다.
posterImageName이 'myImage'의 파일 이름을 저장하고 trailerVideoName은 'myVideo'의 파일 이름을 저장하여 데이터베이스에서 가져올 때 이미지와 비디오를 표시 할 수 있도록합니다. 내 동영상 문서에서 이러한 파일 이름을 설정하고 데이터베이스에 저장하려고하면 다음 오류가 발생합니다. "Undefined의 'filename'속성을 읽을 수 없습니다."
내 코드는 다음과 같습니다.
const upload = multer({
storage: multer.diskStorage({
destination: (req, file, cb) => {
cb(null, './public/uploads/')
},
filename: (req, file, cb) => {
cb(null, `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`);
},
}),
limits: {fileSize: 10000000000},
fileFilter: (req, file, cb) => {
// Allowed ext
const filetypes = /jpeg|jpg|png|gif|mp4/;
// Check ext
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
// Check mimetype
const mimetype = filetypes.test(file.mimetype);
if (mimetype && extname) {
return cb(null, true);
} else {
cb('Error: Images and Videos Only')
}
}
})
router.post('/movies', upload.fields([{name: 'myImage'}, {name: 'myVideo'}]), (req, res) => {
const movie = new Movie({
title: req.body.title,
posterImageName: req.files[0].filename,
trailerVideoName: req.files[1].filename
})
movie.save((error, movie) => {
if (error) return console.error(error);
console.log(`${movie.title} saved to movies collection`);
});
})
나는 upload.fields () 사용 방법에 대한 좋은 설명을 검색하려고 시도했지만 내가 본 모든 자습서 및 포럼에서 upload.single () 또는 upload.array ()에 대해 이야기하기 때문에 찾을 수 없습니다. 다른 코드가 필요하면 알려주세요. 모든 도움에 감사드립니다. :)
그것은 multer 의 README.md 문서에 언급되어 있습니다.
// req.files is an object (String -> Array) where fieldname is the key, and the value is array of files // // e.g. // req.files['avatar'][0] -> File // req.files['gallery'] -> Array // // req.body will contain the text fields, if there were any
기본적으로 필드의 이름은 req.files
const movie = new Movie({
title: req.body.title,
posterImageName: req.files['myImage'][0].filename,
trailerVideoName: req.files['myVideo'][0].filename
})
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다