5 글 보임 - 1 에서 5 까지 (총 5 중에서)
-
글쓴이글
-
2022년 10월 19일 17:14 #50852

Login참가자
이와 같이 사진이랑 게시글을 같이 올리는 폼을 만들려고 하는데, 사진과 같이 전송을 하면 잘 전송이 되지만
사진 없이 전송을 하려고 하면
TypeError: Cannot read properties of undefined (reading 'originalname')
와 같은 에러가 나타납니다.
우선 ejs코드는 다음과 같습니다.
<div id="comments">
<form action="/posts" method="POST" enctype="multipart/form-data">
<div class="block clear">
<input type="date" name="starttime">
<textarea name="comment" id="comment" cols="25" rows="4"></textarea>
</div>
<div>
<label for="input-file">
사진 추가
</label>
<input type="file" id="input-file" name="inputFile2"/>
<br>
<input type="submit" name="submit" value="글 쓰기">
</div>
</form>
</div>
그리고 server.js의 코드는 다음과 같습니다.
app.post('/posts', upload.single('inputFile2'), function (req, res) { var time = req.body.starttime; var times = time.split('-'); console.log(times[0]); console.log(times[1]); console.log(times[2]);db2.collection('counter').findOne({ name: '게시물갯수' }, function (err, result) { // console.log(result.totalPost); var 총게시물갯수 = result.totalPost;db2.collection('timeline').insertOne({ _id: 총게시물갯수 + 1, year: times[0], month: times[1], day: times[2], comment: req.body.comment, imagename: req.file.originalname }, function (err, result) { console.log('저장완료');db2.collection('gallery').insertOne({ _id: 총게시물갯수 + 1, name: req.file.originalname }, function () { console.log('저장완료'); db2.collection('counter').updateOne({ name: '게시물갯수' }, { $inc: { totalPost: 1 } }, function (err, result) { if (err) { return console.log(err) }; res.redirect('/timeline'); }); }); }); }); });여러 방면으로 코드를 수정해봤지만 계속 똑같은 오류가 나타나서 혹시 방법이 없나 여쭤봅니다.... multer을 사용하여 이미지 업로드 시에는 반드시 이미지를 업로드 해야만 사용이 가능한 건가요?
2022년 10월 19일 18:56 #50875
codingapple키 마스터사진이 없으면 req.file.originalname 같은거 저장하지 말라고 if문같은거 추가하면 될듯요
2022년 10월 20일 16:04 #50959
Login참가자네. 그런데 제가 그렇게 시도해봤는데,
app.post('/posts', upload.single('inputFile2'), function (req, res) { console.log(req.file.originalname); }); 이렇게 사진파일을 넣지 않으면 originalname의 값이 맞지 않다고 오류 자체가 뜹니다. var로 다른 인수에 할당하려고 해도 originalname을 언급하면 무조건 오류가 떠서, 해결법을 모르겠습니다... TypeError: Cannot read properties of undefined (reading 'originalname') 다른 값의 경우, 값이 할당되지 않아도 console.log로 확인해보면 undefined 값이 뜨지 오류가 나지는 않더라고요. 마찬가지로 console.log(req.file);을 입력했을 때도 사진 파일을 업로드 하지 않으면 그냥 undefined라고 뜹니다... originalname만 typeerror가 뜨는데 해결방법이 있을까요?2022년 10월 20일 19:57 #50986
codingapple키 마스터if (req.file){ console.log(req.file.originalname); } 합시다 -
글쓴이글
5 글 보임 - 1 에서 5 까지 (총 5 중에서)
- 답변은 로그인 후 가능합니다.
