dataURLtoFile(dataurl, filename) {
//转成blob
function dataURLtoBlob(toDataURL) {
var arr = toDataURL.split(","),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
var blob = null;
// 解决低版本浏览器没有new Blob()问题
try {
blob = new Blob([u8arr], { type: mime });
} catch (e) {
var BlobBuilder = window.BlobBuilder = (
window.BlobBuilder ||
window.WebKitBlobBuilder ||
window.MozBlobBuilder ||
window.MSBlobBuilder
);
if (e.name === "TypeError" && BlobBuilder) {
var builder = new BlobBuilder();
builder.append(u8arr);
blob = builder.getBlob(mime);
}
}
return blob;
}
//转成file
function blobToFile(Blob, fileName) {
Blob.lastModifiedDate = new Date();
Blob.name = fileName;
return Blob;
}
// 调用如下
let bold = dataURLtoBlob(dataurl);
let file = blobToFile(bold, "fileName");
// 上传file就可以了
return file;
}
// ...
// 案例是截取视频第一帧图片
// file是视频文件
var imgFile = that.dataURLtoFile(
canvas.toDataURL("image/png"),
file.name.split(".")[0] + ".png"
);
var fd = new FormData();
// 这里的第三个参数传一个带后缀名的文件名,避免认为不是有效的图片文件
fd.append("file",imgFile,file.name.split(".")[0] + ".png");
$.ajax({
type: "post",
url: '上传路径',
data: fd,
contentType: false,
processData: false //这两个属性不能省
})
.then(res => {
console.log('上传成功');
})