最近在项目中有这么一个需求,就是上传一个视频文件,然后要获取视频文件的第一帧图片,这个可以通过canvas获取得到,得到的是一个dataurl,之后还要将这个图片上传到云,这个时候如何操作就不清楚了,于是乎,google一番,总结如下:
将dataurl转成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
// 假设一个dataurl
const imageurl = "转成base64的变量";
// 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){
},
});