我需要上传一个图像到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转换为一个文件,它对我来说非常有用。
香草JavaScript
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;
}
TypeScript(使用正确的类型)
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");
我已经使用FileSaver.js将blob保存为文件。
这是回购:https://github.com/eligrey/FileSaver.js/
用法:
import { saveAs } from 'file-saver';
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");
saveAs("https://httpbin.org/image", "image.jpg");