프론트에서 이미지와 DTO를 백엔드로 보내줄 필요가 있었다.
단순히 body에 담아서 다 보내주면 될거라는 막연한 생각을 했지만, 어림도 없었다.
여러 시행착오를 겪으며 해결책을 찾게 되었으며, 이에 대해 글을 작성해보는 시간을 가져보겠다.
Content-Type: text/html; charset=utf-8
Content-Type: multipart/form-data; boundary=something
application/octet-stream
으로 사용됨Content-Disposition
, Content-Type
이 존재Content-Type: multipart/form-data; boundary=aBoundaryString
(other headers associated with the multipart document as a whole)
--aBoundaryString
Content-Disposition: form-data; name="myFile"; filename="img.jpg"
Content-Type: image/jpeg
(data)
--aBoundaryString
Content-Disposition: form-data; name="myField"
(data)
--aBoundaryString
(more subparts)
--aBoundaryString--
<form
action="http://localhost:8000/"
method="post"
enctype="multipart/form-data">
<label>Name: <input name="myTextField" value="Test" /></label>
<label><input type="checkbox" name="myCheckBox" /> Check</label>
<label>
Upload file: <input type="file" name="myFile" value="test.txt" />
</label>
<button>Send the file</button>
</form>
POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:50.0) Gecko/20100101 Firefox/50.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1
Content-Type: multipart/form-data; boundary=---------------------------8721656041911415653955004498
Content-Length: 465
-----------------------------8721656041911415653955004498
Content-Disposition: form-data; name="myTextField"
Test
-----------------------------8721656041911415653955004498
Content-Disposition: form-data; name="myCheckBox"
on
-----------------------------8721656041911415653955004498
Content-Disposition: form-data; name="myFile"; filename="test.txt"
Content-Type: text/plain
Simple file.
-----------------------------8721656041911415653955004498--
let formData = new FormData();
formData.append(
'recipeCreateRequestDto',
new Blob([JSON.stringify(recipeCreateDto)], { type: 'application/json' }),
);
if (recipeCreateImage === null) {
formData.append('recipeCreateImage', new Blob());
} else {
let recipeCreateImageType;
if (recipeCreateImage.type == 'image/png') {
recipeCreateImageType = 'image/png';
} else {
recipeCreateImageType = 'image/jpeg';
}
formData.append(
'recipeCreateImage',
new Blob([recipeCreateImage], { type: recipeCreateImageType }),
);
}
fetch(HOST + `/api/v1/recipes`, {
method: 'POST',
body: formData,
})
.then((res) => res.json());
https://developer.mozilla.org/ko/docs/Web/HTTP/Basics_of_HTTP/MIME_types