Convert blob to file

后端 未结 4 1122
半阙折子戏
半阙折子戏 2020-12-24 03:10

I need to convert a blob to file i javascript.

Im using File API

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

This is r

相关标签:
4条回答
  • 2020-12-24 03:21

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

    0 讨论(0)
  • 2020-12-24 03:30

    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;
      }
    
    0 讨论(0)
  • 2020-12-24 03:31

    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.

    0 讨论(0)
  • 2020-12-24 03:40

    in Edge and Safari, just use blob structure:

    var blob = new Blob(byteArrays, { type: contentType });
    blob.lastModifiedDate = new Date();
    blob.name = name;
    
    0 讨论(0)
提交回复
热议问题