如何在 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 转换为文件以上传图像的方法。

有人可以帮我吗?

原文由 skip 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.8k
2 个回答

此函数将 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 (具有正确的类型)

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

原文由 FiniteLooper 发布,翻译遵循 CC BY-SA 3.0 许可协议

打字稿

public blobToFile = (theBlob: Blob, fileName:string): File => {
 return new File(
 [theBlob as any], // cast as any
 fileName,
 {
 lastModified: new Date().getTime(),
 type: theBlob.type
 }
 )
 }

Javascript

 function blobToFile(theBlob, fileName){
 return new File([theBlob], fileName, { lastModified: new Date().getTime(), type: theBlob.type })
 }

输出

截屏

 File {name: "fileName", lastModified: 1597081051454, lastModifiedDate: Mon Aug 10 2020 19:37:31 GMT+0200 (Eastern European Standard Time), webkitRelativePath: "", size: 601887, …}
 lastModified: 1597081051454
 lastModifiedDate: Mon Aug 10 2020 19:37:31 GMT+0200 (Eastern European Standard Time) {}
 name: "fileName"
 size: 601887
 type: "image/png"
 webkitRelativePath: ""
 __proto__: File

原文由 Hossam EL-Kashef 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏