JS fetch API로 파일을 어떻게 업로드합니까?
나는 여전히 내 머리를 감싸려고합니다.
사용자가 파일 입력으로 파일 (또는 여러 개)을 선택할 수 있습니다.
<form>
<div>
<label>Select file to upload</label>
<input type="file">
</div>
<button type="submit">Convert</button>
</form>
그리고를 submit
사용 하여 이벤트를 잡을 수 있습니다 <fill in your event handler here>
. 그러나 일단 내가 한 다음을 사용하여 파일을 보내려면 어떻게해야 fetch
합니까?
fetch('/files', {
method: 'post',
// what goes here? What is the "body" for this? content-type header?
}).then(/* whatever */);
주석이 포함 된 기본 예입니다. upload
기능은 당신이 찾고있는 것입니다 :
// Select your input type file and store it in a variable
const input = document.getElementById('fileinput');
// This will upload the file after having read it
const upload = (file) => {
fetch('http://www.example.net', { // Your POST endpoint
method: 'POST',
headers: {
// Content-Type may need to be completely **omitted**
// or you may need something
"Content-Type": "You will perhaps need to define a content-type here"
},
body: file // This is your file object
}).then(
response => response.json() // if the response is a JSON object
).then(
success => console.log(success) // Handle the success response object
).catch(
error => console.log(error) // Handle the error response object
);
};
// Event handler executed when a file is selected
const onSelectFile = () => upload(input.files[0]);
// Add a listener on your input
// It will be triggered when a file will be selected
input.addEventListener('change', onSelectFile, false);
나는 이렇게했다 :
var input = document.querySelector('input[type="file"]')
var data = new FormData()
data.append('file', input.files[0])
data.append('user', 'hubot')
fetch('/avatars', {
method: 'POST',
body: data
})
Fetch API로 파일을 보내기위한 중요한 참고 사항
content-type
Fetch 요청을 위해 헤더 를 생략해야합니다 . 그런 다음 브라우저는 Content type
다음과 같은 Form Boundary를 포함하여 헤더를 자동으로 추가합니다.
Content-Type: multipart/form-data; boundary=—-WebKitFormBoundaryfgtsKTYLsT7PNUVD
양식 경계는 양식 데이터의 구분 기호입니다.
배수 파일 을 원한다면 이것을 사용할 수 있습니다
var input = document.querySelector('input[type="file"]')
var data = new FormData()
for (const file of input.files) {
data.append('files',file,file.name)
}
fetch('/avatars', {
method: 'POST',
body: data
})
To submit a single file, you can simply use the File
object from the input
's .files
array directly as the value of body:
in your fetch()
initializer:
const myInput = document.getElementById('my-input');
// Later, perhaps in a form 'submit' handler or the input's 'change' handler:
fetch('https://example.com/some_endpoint', {
method: 'POST',
body: myInput.files[0],
});
This works because File
inherits from Blob
, and Blob
is one of the permissible BodyInit
types defined in the Fetch Standard.
Jumping off from Alex Montoya's approach for multiple file input elements
const inputFiles = document.querySelectorAll('input[type="file"]');
const formData = new FormData();
for (const file of inputFiles) {
formData.append(file.name, file.files[0]);
}
fetch(url, {
method: 'POST',
body: formData })
The problem for me was that I was using a response.blob() to populate the form data. Apparently you can't do that at least with react native so I ended up using
data.append('fileData', {
uri : pickerResponse.uri,
type: pickerResponse.type,
name: pickerResponse.fileName
});
Fetch seems to recognize that format and send the file where the uri is pointing.
참고URL : https://stackoverflow.com/questions/36067767/how-do-i-upload-a-file-with-the-js-fetch-api
'IT' 카테고리의 다른 글
rspec-rails를 사용하여 파일 업로드 테스트 (0) | 2020.06.22 |
---|---|
여러 "데이터 토글"을 사용한 부트 스트랩 제어 (0) | 2020.06.22 |
IIS7.5 및 ASP.NET v2의 웹 응용 프로그램 문제 (web.config 오류) HTTP 500.19 (0) | 2020.06.22 |
재귀 적으로 파일 제거 (0) | 2020.06.22 |
objective-c typedef를 해당하는 문자열로 변환 (0) | 2020.06.22 |