如何在JavaScript中将Blob转换为文件
我需要将图像上传到NodeJS服务器到某个目录。我正在connect-busboy
为此使用节点模块。
我dataURL
使用以下代码将图片转换为Blob:
dataURLToBlob: function(dataURL) { var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = decodeURIComponent(parts[1]);
return new Blob([raw], {type: contentType});
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {type: contentType});
}
我需要一种将Blob转换为文件以上传图像的方法。
有人可以帮我吗?
回答:
此函数将a转换Blob
为a File
,对我来说效果很好。
function blobToFile(theBlob, fileName){ //A Blob() is almost a File() - it's just missing the two properties below which we will add
theBlob.lastModifiedDate = new Date();
theBlob.name = fileName;
return theBlob;
}
(具有正确的键入)
public blobToFile = (theBlob: Blob, fileName:string): File => { var b: any = theBlob;
//A Blob() is almost a File() - it's just missing the two properties below which we will add
b.lastModifiedDate = new Date();
b.name = fileName;
//Cast to a File() type
return <File>theBlob;
}
var myBlob = new Blob();//do stuff here to give the blob some data...
var myFile = blobToFile(myBlob, "my-image.png");
以上是 如何在JavaScript中将Blob转换为文件 的全部内容, 来源链接: utcz.com/qa/435986.html