如何在JavaScript中将Blob转换为文件 - 代码日志

如何在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});
}

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

有人可以帮我吗?

此功能将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(适当打字)

function 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");
http://stackoverflow.com/questions/27159179/how-to-convert-blob-to-file-in-javascript

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:如何在JavaScript中将Blob转换为文件