首先,要把 dataURL轉成blob
下面這四點是我在stackoverflow上查到的四個步驟:- Take a bytearray or any other data
- Convert it to base64
- Convert it to blob
- Send it as a normal file with Ajax/xhr/FormData using your favorite method
function (dataURI) { // convert base64 to raw binary data held in a string // doesn't handle URLEncoded DataURIs var byteString = atob(dataURI.split(',')[1]); // separate out the mime component var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; // write the bytes of the string to an ArrayBuffer var ab = new ArrayBuffer(byteString.length); var ia = new Uint8Array(ab); for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } var blob = new Blob([ab]); return blob; }
不要問我上面的code怎麼來的,我抄來的!(挺)
接下來我曾經好傻好天真的認為可以把blob塞進form的欄位中,然後把它submit出去,但最後發現是不可以的...
用Ajax將檔案post出去吧
查了一下發現最方便的方式是使用formData物件,只要只用他的append方法就能把blob或string append上去:
var fd = new FormData(); fd.append("source", blob);接下來只要將他post出去就好囉:
var xhr = new XMLHttpRequest(); xhr.open("POST", url); xhr.send(fd);