Skip to main content

[AWS] S3 API

keywords: aws, s3#

Upload to presigned URL#

  • presigned URL 在 AWS 上記得要開放 PUT 的權限,否則會觸發 CORS
  • headers 的 Content-Type 要加上 application/octet-stream
  • 上傳的內容會是 Blob 物件

透過 Fetch API#

// data 是透過 <input type="file" /> 在 change 事件取得的 e.target.files[0]function uploadFileWithFetch(data) {  return fetch(presignedURL, {    method: 'PUT',    body: data,    headers: {      'Content-Type': 'application/octet-stream',    },  })    .then((response) => response.text())    .then((data) => console.log('data', data))    .catch((error) => console.log('error', error));}

透過 XMLHttpRequest (XHR) 可取得上傳進度#

function uploadFile(data) {  return new Promise((resolve, reject) => {    const xhr = new XMLHttpRequest();
    xhr.upload.addEventListener('progress', updateProgress);    xhr.upload.addEventListener('load', transferComplete);    xhr.upload.addEventListener('error', transferFailed);
    xhr.open('PUT', presignedURL);
    xhr.setRequestHeader('Content-Type', 'application/octet-stream');    xhr.send(data);
    function updateProgress(event) {      if (event.lengthComputable) {        var percentComplete = event.loaded / event.total;        console.log('percentComplete', percentComplete);      } else {        console.log('Unable to compute progress information since the total size is unknown');      }    }
    function transferComplete(evt) {      console.log('The transfer is complete.');      resolve('complete');    }
    function transferFailed(evt) {      console.log('An error occurred while transferring the file.');      reject('An error occurred while transferring the file.', evt);    }  });}