1. 程式人生 > >fetch上傳檔案

fetch上傳檔案

通過簡單的配置,實現form表單檔案上傳

var formData = new FormData();
var fileField = document.querySelector("input[type='file']");

formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]);

fetch('https://example.com/profile/avatar', {
  method: 'PUT',
  body: formData
})
.then(response 
=> response.json()) .catch(error => console.error('Error:', error)) .then(response => console.log('Success:', response));