HTML code
<input id="file-input" accept="image/png, image/jpeg" type="file" name="name" />
after selecting the image , I run this code
var file = $("#file-input").val();
console.log(getBase64(file));
here's the getBase64 function
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
this function fires this error :
Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not
of type 'Blob'.
that's what I tried - if you have workable answer = please share it
Try changing
var file = $("#file-input").val();
to
var file = $("#file-input")[0].files[0];
.val() is not actually returning the blob/file object that you want in this case.
Related
I need to create the ability to attach pictures and send them via JSON in base64.
But I can't get the resulting string from FileReader object. I will be very grateful if you can tell me how to fix this.
<form>
<label>Picture
<input type="file" accept=".jpg, .jpeg, .png" name="picture" required>
</label>
</form>
async function push() {
// some other actions here
let form = new FormData(document.querySelector('form'));
let json = construct_json(form);
//calls of other functions
}
function getBase64(file) {
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () { // I think there is a mistake here.
reader.result;
};
}
function construct_json(form) {
let json = {
picture: getBase64(form.get('picture')),
};
return JSON.stringify(json);
}
UPD:
If I'm trying to use json in the push() function then I get the same problem. And adding await doesn't help. I would be grateful for a hint how can I display json in the push() function?
Yes. You are making a mistake when reader.onload method gets envoke. You can find example here
You forget to addEventListener and callback when upload gets done. Please add the following code
window.addEventListener("change", push);
function getBase64(file, callback) {
let reader = new FileReader();
reader.onload = function(e) {
// console.log(e.target);
// I think there is a mistake here
callback(e.target.result);
};
reader.onloadend = function(e) {
return e.target.result;
};
return reader.readAsDataURL(file);
}
async function construct_json(form) {
await getBase64(form.get("picture"), data => {
let json = {
picture: data
};
return JSON.stringify(json);
});
}
Updating the answer based on comment. you can refer to the example on sandbox
Please add create a promise to avoid callback hell. Here I have promised the base46 Function. Promisification
const getBase64Promise = function (file) {
return new Promise((resolve, reject) => {
getBase64(file, (success,err) => {
if(err) reject(err)
else resolve(success);
});
});
};
Like this
async function construct_json(form, callback) {
let data = await getBase64Promise(form.get("picture"));
let json = {
picture: data
};
return json;
}
I've got a form for uploading Avatar image and I have to send the image file in the format of binary string; so far I've tried ReadAsBinaryString from FileReader but it's not working:(
here's my code:
<form onSubmit={this.onFormSubmit}>
<div className="row justify-content-center mb-2">
<input type="file" id="avatar" accept="image/png, image/jpeg"
onChange={this.uploadedImage} />
<button type="submit" className="btn btn-sm btn-info">Send</button>
</div>
</form>
and that is how I'm trying to use ReadAsBinaryString in uploadedImage function:
uploadedImage(e) {
let reader = new FileReader();
let file = e.target.files[0];
console.log(file); //I can see the file's info
reader.onload= () => {
var array = new Uint32Array(file);
console.log("_+_array:",array); // the array is empty!
var binaryString = String.fromCharCode.apply(null,array) ;
console.log("__binaryString:",binaryString);
this.setState({
file: binaryString
},()=>{
console.log(this.state.file);//ergo file is set to an empty image
});
}
reader.readAsArrayBuffer(file)
}
so to sum it up, I get a file but I can't convert it to byte array; Is there anything wrong with this code or this approach is completely wrong?
This approach worked for me:
function readFileDataAsBase64(e) {
const file = e.target.files[0];
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (event) => {
resolve(event.target.result);
};
reader.onerror = (err) => {
reject(err);
};
reader.readAsDataURL(file);
});
}
You can call reader.readAsBinaryString() if you wish to use binary string. More here: https://developer.mozilla.org/en-US/docs/Web/API/FileReader
You are trying to read the file data using the file variable which contains the file info not the file contents. Try sth like the following:
FileReader documentation
uploadedImage(e) {
let reader = new FileReader();
let file = e.target.files[0];
console.log(file); //I can see the file's info
reader.onload= () => {
var array = new Uint32Array(reader.result); // read the actual file contents
console.log("_+_array:",array); // the array is empty!
var binaryString = String.fromCharCode.apply(null,array) ;
console.log("__binaryString:",binaryString);
this.setState({
file: binaryString
},()=>{
console.log(this.state.file);//ergo file is set to an empty image
});
}
reader.readAsArrayBuffer(file)
}
Just to add to tomericco's answer, here is one with few more lines to get the actual final byte array :
const test_function = async () => {
... ... ...
const get_file_array = (file) => {
return new Promise((acc, err) => {
const reader = new FileReader();
reader.onload = (event) => { acc(event.target.result) };
reader.onerror = (err) => { err(err) };
reader.readAsArrayBuffer(file);
});
}
const temp = await get_file_array(files[0])
console.log('here we finally ve the file as a ArrayBuffer : ',temp);
const fileb = new Uint8Array(fileb)
... ... ...
}
where file is directly the File object u want to read , this has to be done in a async function...
const file = e.target.files[0];
// we need to get the raw bytes
const buffer = await file.arrayBuffer();
// each entry of array should contain 8 bits
const bytes = new Uint8Array(buffer);
How to get string Base64 from an input file .pdf.
i have this function but i dont return the string base64.
the files extencion accept are .pdf
I NEED THE STRING BASE64 IN AN VARIABLE
My code:
<input type="file" id="files" name="files" multiple>
Js code
var base64 = getBase64(document.getElementById('files').files[0])
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
return(reader.result); //THIS NO RETURN NOTHING. WHY?
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
I tested it, it works, you have to add it on the change event, you are calling the getbase64 before anything is there:
https://jsfiddle.net/ibowankenobi/fcgL3dn8/
document.getElementsByTagName("input")[0].addEventListener("change",getBase64,false);
var _file;
function getBase64() {
var file = this.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
_file = reader.result;
//don't do the below. It is pointless. Either assign the result to a variable within scope or call a callback
//return(reader.result); //THIS NO RETURN NOTHING. WHY?
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
<script>
var file = document.getElementById("userFile").files[0];
var reader = new FileReader();
reader.readAsArrayBuffer(file);
var byteArray = reader.result;
console.log(byteArray);
</script>
This code produces this error in the console: Failed to execute 'readAsArrayBuffer' on 'FileReader': parameter 1 is not of type 'Blob'.
To my understanding, a FileReader can accept both a Blob and File as a parameter because the File interface is based upon Blob.
FileReader requires the use of it's .onload property to trigger a callback when readAsArrayBuffer (and other FileReader methods) has completed. The snippet below includes an example of how it could be used in tandem with the onChange event for a file input:
const input = document.getElementById('userFile');
const reader = new FileReader();
input.onchange = function() {
const file = input.files[0];
reader.readAsArrayBuffer(file);
};
reader.onload = function() {
const resultArray = new Int8Array(reader.result);
document.getElementById('result').innerHTML = resultArray;
};
<input type="file" id="userFile"/>
<h4>File Data:</h4>
<span id="result"/>
I wish to read the contents of an upload file into a Javascript variable.
The program used to work using file.getAsBinary but this is now deprecated and needs to be updated to use FileReader()
A form has a file upload selection an onsubmit runs a function uploadDB() in a javascript.
The variable dbname is passed okay as is the file name from the upload selection
I can see it with an alert or console.log.
The final bfile variable to receive the file text is undefined. I have tried both readAsText and ReadAsBinary but bfile is undefined. The var declaration is in function uploadDB() and should be global to the inner function. If scope is somehow a problem how do I get the result in the bfile variable.
Its probably simple but I cannot get it to work. Can someone suggest something please.
The html section is;
<form onsubmit="uploadDB()"; method="post">
Database <input type=text name="dbName" id="dbName" size=20>
<input type=file id="metaDescFile" size=50 >
<input type=submit value="Submit">
</form>
The js script is similar to (extraneous stuff edited out);
<script language="javascript" type="text/javascript">
<!--
var uploadDB = function() {
var input = document.getElementById('metaDescFile');
var fname = document.getElementById('metaDescFile').value;
var file=input.files[0];
var bfile;
reader = new FileReader();
reader.onload = function(e) { bfile = e.target.result }
reader.readAsText(file);
alert(bfile); // this shows bfile as undefined
// other stuff
}
as bfile gets set in the onload callback you won't be able to access outside that callback because the code is evaluated before the callback is fired.
Try this:
reader = new FileReader();
reader.onload = function(e) {
bfile = e.target.result
alert(bfile); // this shows bfile
}
reader.readAsText(file);
Here is one answer to get the actual final byte array , just using FileReader and ArrayBuffer :
const test_function = async () => {
... ... ...
const get_file_array = (file) => {
return new Promise((acc, err) => {
const reader = new FileReader();
reader.onload = (event) => { acc(event.target.result) };
reader.onerror = (err) => { err(err) };
reader.readAsArrayBuffer(file);
});
}
const temp = await get_file_array(files[0])
console.log('here we finally ve the file as a ArrayBuffer : ',temp);
const fileb = new Uint8Array(fileb)
... ... ...
}
where file is directly the File object u want to read , notice that this is an async function...