简体   繁体   中英

Convert blob to file

I need to convert a blob to file i javascript.

Im using File 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.

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

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.

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..

in Edge and Safari, just use blob structure:

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

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

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

https://stackoverflow.com/a/62227874/13081559

// here file_name will be name of that particular file 

let fileData =  function dataURLtoFile(base64, file_name) {
 var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
 bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
 while(n--){
 u8arr[n] = bstr.charCodeAt(n);
 }
return new File([u8arr], filename, {type:mime});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM