SPA File donwload
方法 1
- request by ajax
- response binary data to client
- save binary data by file on client
方法 2
- request by ajax
- response with file (direct) download URL
- (async) server create file and save file
- file can download from 2's URL
でも、保存されているfile pathを隠したい場合には結局 1の方法になるのかな
方法 3 (1 + 2)
- request by ajax
- response with file (ajax) download URL(or key?)
- (async) server create file and save file
- request file by ajax by 2's URL
- search file by URL's parameter
- response file's binary data to client
- save binary data by file on client
方法 3+ (aws s3)
- request by ajax
- response with file (ajax) download URL(or key for parameter)
- (async) server create file and save file to s3
- update batch status when file uploaded.
- request file by ajax by 2's URL
- search file from s3 by URL's parameter
- If file exist create s3 download URL with expired time.
- response s3 download URL to client
- download file directly from s3 by response URL.
最終的に使ったコード
- https://stackoverflow.com/questions/17696516/download-binary-files-with-javascript
- https://developer.mozilla.org/ja/docs/XMLHttpRequest/Sending_and_Receiving_Binary_Data
server 部分
- file生成
- s3 upload
- 期限付き s3 URLを発行
- json responseへ返す
js 部分
someApi.createFile(order.id).then(payload => {
var oReq = new XMLHttpRequest()
oReq.open("GET", payload.fileUrl, true)
oReq.setRequestHeader('Content-Type', payload.contentType);
oReq.responseType = "arraybuffer"
oReq.onload = function (oEvent) {
if (this.status === 200) {
var blob = new Blob([oReq.response], { type: payload.contentType })
var objectUrl = URL.createObjectURL(blob)
let a = document.createElement('a')
a.download = payload.fileName
a.href = objectUrl
a.click()
}
}
oReq.send()
})