Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert blob to file

Tags:

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

like image 309
Delete me Avatar asked Dec 18 '14 18:12

Delete me


People also ask

How do I turn a blob into a file?

To convert Blob to File in JavaScript, we can use the File constructor. const file = new File([myBlob], "name"); to create a File object with the myBlob blob object in the array. The 2nd argument is the file name string.

Is Blob a file?

The Blob object represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a ReadableStream so its methods can be used for processing the data. Blobs can represent data that isn't necessarily in a JavaScript-native format.

How can I convert BLOB to JPG?

getContext("2d"); // Get the "context" of the canvas var img = document. getElementById("myimage"); // The id of your image container ctx. drawImage(img,0,0,width,height); // Draw your image to the canvas var jpegFile = canvas. toDataURL("image/jpeg"); // This will save your image as a //jpeg file in the base64 format.


2 Answers

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.

like image 64
cuixiping Avatar answered Oct 23 '22 05:10

cuixiping


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

like image 29
Delete me Avatar answered Oct 23 '22 07:10

Delete me