且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2021-07-20 22:52:04

此函数将 Blob 转换为 File,对我来说效果很好.

This function converts a Blob into a File and it works great for me.

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