Javascript 将 blob 转换为文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27553617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:18:49  来源:igfitidea点击:

Convert blob to file

javascript

提问by Delete me

I need to convert a blob to file i javascript.

我需要将 blob 转换为 javascript 文件。

Im using File API

我正在使用文件 API

var blob = new Blob(byteArrays, { type: contentType });

This is return from a function reading a cropped images.

这是从读取裁剪图像的函数返回的。

The old upload function are using $files as input.

旧的上传功能使用 $files 作为输入。

I want to convert that blob to file, and then set the name and type in that object. How do I do this??

我想将该 blob 转换为文件,然后在该对象中设置名称和类型。我该怎么做呢??

回答by cuixiping

It's easy:

这很简单:

var blob = new Blob(byteArrays, { type: contentType });
var file = new File([blob], filename, {type: contentType, lastModified: Date.now()});

or just:

要不就:

var file = new File([byteArrays], filename, {type: contentType, lastModified: Date.now()});

The code works in Chrome and Firefox, but not IE.

该代码适用于 Chrome 和 Firefox,但不适用于 IE。

回答by Delete me

I solved the file problem like this:

我解决了这样的文件问题:

    function base64ToFile(base64Data, tempfilename, contentType) {
    contentType = contentType || '';
    var sliceSize = 1024;
    var byteCharacters = atob(base64Data);
    var bytesLength = byteCharacters.length;
    var slicesCount = Math.ceil(bytesLength / sliceSize);
    var byteArrays = new Array(slicesCount);

    for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
        var begin = sliceIndex * sliceSize;
        var end = Math.min(begin + sliceSize, bytesLength);

        var bytes = new Array(end - begin);
        for (var offset = begin, i = 0 ; offset < end; ++i, ++offset) {
            bytes[i] = byteCharacters[offset].charCodeAt(0);
        }
        byteArrays[sliceIndex] = new Uint8Array(bytes);
    }
    var file = new File(byteArrays, tempfilename, { type: contentType });
    return file;
}

Next problem is the format that angular-file-upload is reading the file in..

下一个问题是 angular-file-upload 正在读取文件的格式..

回答by Xuejun

in Edge and Safari, just use blob structure:

在 Edge 和 Safari 中,只需使用 blob 结构:

var blob = new Blob(byteArrays, { type: contentType });
blob.lastModifiedDate = new Date();
blob.name = name;

回答by NanoWar

In IE10 there is no File constructor, but you can use the following in typescript:

在 IE10 中没有 File 构造函数,但您可以在打字稿中使用以下内容:

private createFile(bytes: string, name: string): File {
    const file: File = <File>Object.assign(new Blob([bytes]), { lastModifiedDate: new Date(), name: name });
    return file;
  }