Technical/etc
[express] fetch를 사용하여 formdata를 넘길 때, files을 전달하는 방법(React/Express/Multer)
sga8
2020. 7. 1. 18:11
728x90
구글링 검색어
- Fetch React Express req.files undefined
- Multer array req.files undefined
- upload files from react to express
환경
- React (front-end) / Express (back-end)
- Express에서는 Multer를 사용하여 파일을 저장하려고 함.
사용 방법
1) Form 태그 사용 (<Form></Form>)
<form
encType="multipart/form-data"
action="/api/post/scriptupload"
method="POST
>
- 이 방법을 사용해서 전달했을 때의 문제점은 response를 받아오는 방법을 모르겠다는 거. (아직 모름)
2) Fetch를 사용하여 new FormData()를 넘겨 받아쓰는 방법
const formData = new FormData();
formData.append("imsi", target.imsi.value);
for (let i = 0; i < target.fileToUpload.files.length; i++) {
formData.append("uploadFiles", target.fileToUpload.files[i]);
}
fetch("/api/post/scriptupload", {
method: "POST",
body: formData
})
.then(response => response.json())
.then(res => {
console.log(res);
});
- React(front-end)에서는 위와 같은 방식으로 formdata를 만들고, fetch를 하면됨.
- files을 한번에 넣으면 multer가 array로 인식을 못하는 것으로 보임. for문으로 하나씩 append해줘야함
let multer = require("multer");
const moment = require("moment");
const storage = multer.diskStorage({
destination: "./test",
filename: function(req, file, cb) {
cb(null, moment().format("YYYYMMDDHHmmss") + "_" + file.originalname);
}
});
router.post(
"/scriptupload",
multer({ storage: storage }).array("uploadFiles"),
(req, res) => {
}
);
- Express(back-end)에서는 위와 같이 설정을 해준다.
- diskStorage 관련된 설명은 multer github에서 매우 쉽게 찾을 수 있으니 패스.
- 여기서 중요한 부분은 multer를 array로 받는데, "uploadFiles"라는 parameter를 사용한 것임.
- React(front-end)에서 formData에 데이터를 담을 때, uploadFiles라고 지정했기 때문에 무조건 동일 해야함.
이렇게 하면 무조건 됩니다
728x90