IT

JS fetch API로 파일을 어떻게 업로드합니까?

lottoking 2020. 6. 22. 07:31
반응형

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-typeFetch 요청을 위해 헤더 를 생략해야합니다 . 그런 다음 브라우저는 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

반응형