最近在項目中有這么一個需求,就是上傳一個視頻文件烫扼,然后要獲取視頻文件的第一幀圖片滓窍,這個可以通過canvas獲取得到,得到的是一個dataURL,之后還要將這個圖片上傳到云了赌,這個時候如何操作就不清楚了臊泌,于是乎,google一番揍拆,總結(jié)如下:
- 將dataURL轉(zhuǎn)成Blob
- 利用formData
- 異步上傳
function b64toBlob(b64Data, contentType='', sliceSize=512) {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, {type: contentType});
return blob;
}
// dataURL to blob
// 假設(shè)一個dataURL
const ImageURL = "data:image/jpeg;base64,abcdefg
// Split the base64 string in data and contentType
const block = ImageURL.split(";");
// Get the content type of the image
const contentType = block[0].split(":")[1];// In this case "image/jpeg"
// get the real base64 content of the file
const realData = block[1].split(",")[1];// In this case "R0lGODlhPQBEAPeoAJosM...."
// Convert it to a blob to upload
var blob = b64toBlob(realData, contentType);
// new a formData
const formData = new FormData();
formData.append('blob', blob);
// upload
$.ajax({
url:url,
data: formData
type:"POST",
contentType:false,
processData:false,
error:function(err){
},
success:function(data){
},
});