Uncaught DOMException: Failed to execute 'readAsDataURL' on 'FileReader' - javascript

I have been task to create and upload image file but i am having issue with the blob and base64 items the Blob URL is working as expected but when i try to use a FileReader it is showing the item is busy reading blob. I have also tried to remove the code files for URL the retain the File Reader code but still same issues. And also how the onload is called every time how to stop it after the base64 is created. Or is it also posible to convert the blob URL to a base64
uploadImageChange(e){
const file = e.target.files[0];
this.showImageModalErrorMessage = false;
let fileReader = new FileReader();
fileReader.onload = function(fileLoad){
console.log(fileReader.readAsDataURL(file));
}
if(file.size < 2000){
this.imageSelectedUrl = URL.createObjectURL(file);
this.showImageSaveContent = true;
this.modalSecondInstruction = true;
}else{
this.imageModalErrorMessage = "The image you chose is bigger than 2 MB. Kindly upload a smaller-sized photo."
this.showImageModalErrorMessage = true;
}
},

Try this way
let fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function(fileLoad){
consoloe.log(fileReader.result);
}

Had a similar problem, the below code worked for me fine.
fileReader(file: any) {
const reader = new FileReader();
reader.onloadend = () => {
const formData = new FormData();
const blobFile = new Blob([reader.result], { type: file.type });
formData.append("file", blobFile, "filename");
// POST formData call
};
reader.readAsArrayBuffer(file);
}

Related

Download file converted from Blob

In Javascript, test browser is Firefox. I have converted files to an array of bytes to store on my server and have used the subsequent code to convert the bytes back to a file, but I am unsure as to how to download the newly created file with appropriate file type can anyone please direct me?
to blob
$('input[type="file"]').change(function(e){
function convertFile(file){
return Array.prototype.map.call(new Uint8Array(file), x => ('00' + x.toString(16)).slice(-2)).join('');
}
file = event.target.files[0];
fileName = file.name;
fileSplit = fileName.split('.');
last = fileSplit.length-1;
let fileType = fileSplit[last];
$('#FileNameVisible').text(fileName);
var reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function(e) {
fileData = e.target.result;
fileData = convertFile(e.target.result);
console.log(fileData);
};
reader.onerror = function() {
console.log(reader.error);
};
});
from Blob
var file = new File([dataUse], "File", {lastModified: Date.now()});
console.log(file);

Convert buffer to file [FileCollection:meteor/ostrio:files]

when i get the image from the input
i have to convert it to a buffer to make some operations with the image, so as a result a i have a buffer instead of file.
im using FileCollection in meteor to store the image in mongo collection
uploadIt(e) {
e.preventDefault();
var reader = new FileReader();
var buffer;
var file = e.currentTarget.files[0];
if (e.currentTarget.files && e.currentTarget.files[0]) {
reader.onload = function(e){
buffer = new Uint8Array(reader.result);
// some operations over the buffer
};
reader.readAsArrayBuffer(file);
if (file) {
let uploadInstance = CourseFilesCollection.insert({
file: buffer,
..
..
})
}
}
but when i insert it got this error
message: "[FilesCollection] [insert] Have you forget to pass a File itself?
the code originally was
if (file) {
let uploadInstance = CourseFilesCollection.insert({
file: file,
..
..
})
}
but since i had to perfom operations over the the image i need to someway conver the buffer to file
any ideas how to solve this ?
Short answer
use the file constructor to turn bits back to a file container:
file: new File([buffer], file.name, file)
you could try using blob also with wider browser support... but if you want to use the latest tech, then:
async uploadIt (evt) {
evt.preventDefault()
const file = evt.currentTarget.files[0]
if (!file) return
const buffer = new Uint8Array(await file.arrayBuffer())
// some operations over the buffer
const uploadInstance = CourseFilesCollection.insert({
file: new File([buffer], file.name, file)
})
}

How can i read data from blob url?

I have to read the data as an array of characters or even better as an base64 string from a blob url,
for later processing.
The blobUrl that i have to read for example is
blob:https://localhost:44399/a4775972-6cc8-41a3-af64-1180d9941ab0
Actually when following the link, the file is previewed in my browser.
While trying to read the file
var blobUrl = document.getElementById("test").value;
var reader = new FileReader();
reader.readAsDataURL(blobUrl);
reader.onloadend = function ()
{
base64data = reader.result;
console.log(base64data);
}
I get the error
Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.
What am i doing wrong here?
readAsDataURL does not actually accept url as input?
How can i fix that?
As spec says, readAsDataURL accept Blob only (which is File inheritor) as a param.
So you need to use original blob file reference (if you have it) or convert URL into file instance.
To convert image URL into the file itself, you can do the following.
async function convertToFile(url){
let response = await fetch(url);
let blob = await response.blob();
return new File([blob], 'put_the_name.jpg', {
type: 'image/jpeg'
});
}
// usage
async function main() {
const url = document.getElementById("test").value; // get file URL somehow
const file = await convertToFile(url); // usage of function above
const reader = new FileReader();
reader.readAsDataURL(file);
...
}
Or if you have an input in your markup for uploading files (which is popular use case), you can get file reference directly.
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
if (file) {
reader.readAsDataURL(file);
}

file reader read blob file

i am trying to use filereader to access a blob file located locally, such as c drive, then converts it back to object URL as img src. it is not working, can anyone help this?
never found anyone try to access a blob file from disk. what is the blob file type extension?
const imageOut = document.querySelector('#image-out');
imageOut.addEventListener('load', () => {
const reader = new FileReader();
reader.addEventListener('load', () => {
var f = File.createFromFileName("file:///C:/blob.blb");
const arrayBuffer = reader.readAsArrayBuffer(f);
const blob = new Blob([arrayBuffer], { type: mimeType });
imageOut.src = URL.createObjectURL(blob);
});
});
empty, not show
Check how to use blob here it is clearly explained and it should be enough to get you going.
Try this:
Assuming that file:///C:/blob.blb exists and you are sure, then do it like so:
imageOut.addEventListener('load', () => {
const reader = new FileReader();
var f = File.createFromFileName("file:///C:/blob.blb");
reader.addEventListener('load', (e) => {
const arrayBuffer = reader.readAsArrayBuffer(f);
global.blob = new Blob([arrayBuffer], { type: f.type});
});
// notice this is outside the reader Load.
var intval = setInterval(function(){
if(blob !== undefined){
imageOut.src = URL.createObjectURL(blob);
clearInterval(intval);
}
}, 100);
});
I hope it helps.

How to Convert Uploaded Audio to Blob using Javascript?

I am trying to capture the audio that's uploaded by the user, convert it to Blob then using wavesurfer.js to display the waveform.
I am following this instruction here https://bl.ocks.org/nolanlawson/62e747cea7af01542479
And here is the code
// Convert audio to Blob
$('#audioFileInput').on('change', function () {
var file = $('#audioFileInput')[0].files[0];
var fileName = file.name;
var fileType = file.type;
var fileReader = new FileReader();
fileReader.onloadend = function (e) {
var arrayBuffer = e.target.result;
blobUtil.arrayBufferToBlob(arrayBuffer, fileType).then(function (blob) {
console.log('here is a blob', blob);
console.log('its size is', blob.size);
console.log('its type is', blob.type);
surfTheBlob(blob);
}).catch(console.log.bind(console));
};
fileReader.readAsArrayBuffer(file);
});
But it says
blobUtil.arrayBufferToBlob(...).then is not a function
Another issue is that since the user might upload the audio themselves, the audio type might vary, expected to come from native device audio recorder. Anyone can help please? thanks.
A File object, like the ones you get in the input.files FileList, is already a Blob:
inp.onchange = e =>
console.log(inp.files[0] instanceof Blob) // true
<input type="file" id="inp">
So all you really need is to pass directly this File to your library:
$('#audioFileInput').on('change', function () {
var file = this.files[0];
surfTheBlob(file);
});
Found the answer already.
// Convert audio to Blob
$('#audioFileInput').on('change', function () {
var file = $('#audioFileInput')[0].files[0];
var fileName = file.name;
var fileType = file.type;
var url = URL.createObjectURL(file);
fetch(url).then(function(response) {
if(response.ok) {
return response.blob();
}
throw new Error('Network response was not ok.');
}).then(function(blob) {
surfTheBlob(blob);
}).catch(function(error) {
console.log('There has been a problem with your fetch operation: ', error.message);
});
});
Cheers!

Categories

Resources