PJCHENder 未整理筆記

[AWS] S3 API

2019-07-22

[AWS] S3 API

@(雲端服務)

keywords: aws, s3

Upload to presigned URL

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

透過 Fetch API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 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) 可取得上傳進度

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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)
}
})
}

掃描二維條碼,分享此文章