如何在JavaScript中将Blob转换为文件

我需要上传一个映像到NodeJS服务器到某个目录。 我正在使用connect-busboy节点模块。

我有我使用以下代码转换为blob图像的dataURL

 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}); } 

我在客户端使用AngularJS。 我有上传已经写入的文件/图像的代码,所以我需要一种方法来将blob转换为file upload图像。

有人可以帮我吗?

这个函数将一个Blob转换成一个File ,对我来说非常有用。

香草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 (适当的types)

 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"); 

您可以使用File构造函数:

 var file = new File([myBlob], "name"); 

根据w3规范,这将把blob包含的字节附加到新File对象的字节中,并用指定的名字创build文件。http://www.w3.org/TR/FileAPI/#dfn-file

在FileSaver.js github项目上使用saveAs

FileSaver.js在本身不支持它的浏览器中实现saveAs() FileSaver接口。