這幾天在做前端的 form,遇到了不知道該怎麼樣讓 JS 透過 API 送 file 比較好的問題,當然答案是「It depends」在這裡把我的想法記錄下來
送 file 的方法直覺想到會有幾種:
https://imququ.com/post/four-ways-to-post-data-in-http.html
基本上原生的 form 可以支援兩種方式:
* application/x-www-form-urlencoded
* multipart/form-data
但我想要讓我們的 API 都是走 application/json 的格式該怎麼辦呢?
另外一個方法是可以把 file encode 成 base64 的字串傳給後端
要了解每個方法的 pros and cons 可以看以下的討論串:
https://stackoverflow.com/questions/33279153/rest-api-file-ie-images-processing-best-practices
這次我還是選用 base64 走 application/json,原因跟上述很類似,因為
1. 可以讓所有 endpoint 都走 json
2. base64 是很好理解的格式,對 client 不太會造成太大困擾
3. 可以支援同時傳 file 和其他 input
4. performance 比較差沒錯,但可以接受
至於 JS client 轉 base64 就用 FileReader 就行了
```js
const reader = new FileReader()
reader.onload = (event) => {
$.post({
url: "/api/private/messages?order_token=aa325ea3-2f86-4866-865d-6c0771922a59",
data: {
message: {
attachment: event.target.result
}
}
}).done((data) => {
console.log(data)
})
}
reader.readAsDataURL(file)
```
沒有留言:
張貼留言