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??
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.
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.
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.
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..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With