asyncfunctionSavePhoto(inp){let user ={ name:'john', age:34};let formData =newFormData();let photo = inp.files[0];
formData.append("photo", photo);
formData.append("user", JSON.stringify(user));try{let r =await fetch('/upload/image',{method:"POST", body: formData});
console.log('HTTP response code:',r.status);}catch(e){
console.log('Huston we have problem...:', e);}}
<inputid="image-file"type="file"onchange="SavePhoto(this)"><br><br>
Before selecting the file open chrome console > network tab to see the request details.
<br><br><small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small><br><br>
(in stack overflow snippets there is problem with error handling, however in <ahref="https://jsfiddle.net/Lamik/b8ed5x3y/5/">jsfiddle version</a> for 404 errors 4xx/5xx are <ahref="https://stackoverflow.com/a/33355142/860099">not throwing</a> at all but we can read response status which contains code)
<inputid="image-file"type="file"onchange="SavePhoto(this)"><br><br>
Choose file and open chrome console > network tab to see the request details.
<br><br><small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small><br><br>
(the stack overflow snippets, has some problem with error handling - the xhr.status is zero (instead of 404) which is similar to situation when we run script from file on <ahref="https://stackoverflow.com/a/10173639/860099">local disc</a> - so I provide also js fiddle version which shows proper http error code <ahref="https://jsfiddle.net/Lamik/k6jtq3uh/2/">here</a>)
서버 측에서는 브라우저가 filenameformData 매개 변수 에 요청하도록 자동으로 포함 된 원본 파일 이름 (및 기타 정보)을 읽을 수 있습니다 .
당신은 설정 요청 헤더 필요가 없습니다 Content-Type에 multipart/form-data-이 브라우저에 의해 자동으로 설정됩니다.
대신 /upload/image전체 주소를 사용할 수 있습니다 http://.../upload/image.
단일 요청으로 많은 파일을 보내려면 multipleattribute : <input multiple type=... />를 사용하고 선택한 모든 파일을 비슷한 방식으로 formData에 첨부하십시오 (예 : photo2=...files[2];… formData.append("photo2", photo2);)
다음과 같이 요청하기 위해 추가 데이터 (json)를 포함 할 수 있습니다 let user = {name:'john', age:34}.formData.append("user", JSON.stringify(user));