Here i did multiple file images with base64 conversion , everything working fine , for my requirement user select the multiple images and click the submit button means i have to take the values(file) and converted to base64 encoded string,here when select image that time it will working fine but going submit the button i am getting undefined how to solve this error
$(document).ready(function(){
$("input[name=property_images]").change(function() {
var imgBase64Arr = [];
var files = this.files;
for (var i = 0; i < files.length; i++) {
(function(i){
var FR = new FileReader();
FR.onload = function(e) {
var res = e.target.result ;
var arr1 = res.split(",");
var property_image = arr1[1] ;
imgBase64Arr.push( property_image);//adding base64 value to array
if(i === files.length -1)//after all files are porcessed
myFunction(imgBase64Arr)
};
FR.readAsDataURL(files[i]);
})(i);
}
});
});
function myFunction(imgBase64Arr){
console.log(imgBase64Arr);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="file" name="property_images" multiple="multiple" />
<input type="button" value="submit" onclick="myFunction()">
When press submit button you call "myFunction" without passing anything..
$(document).ready(function(){
var imgBase64Arr = [];
$("input[name=uploadBtn]").click(function(){
console.log(imgBase64Arr);
});
$("input[name=property_images]").change(function() {
imgBase64Arr = [];
var files = this.files;
for (var i = 0; i < files.length; i++) {
(function(i){
var FR = new FileReader();
FR.onload = function(e) {
var res = e.target.result ;
var arr1 = res.split(",");
var property_image = arr1[1] ;
imgBase64Arr.push( property_image);//adding base64 value to array
if(i === files.length -1)//after all files are porcessed
myFunction(imgBase64Arr)
};
FR.readAsDataURL(files[i]);
})(i);
}
});
});
function myFunction(imgBase64Arr){
console.log(imgBase64Arr);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="file" name="property_images" multiple="multiple" />
<input type="button" name="uploadBtn" value="submit">
Your imgBase64Arr variable is not globally defined. Please defined it globally.
Related
I want to upload multiple images to my firebase database at once. I will be needing HTML as well.
Here is what I have found by research, but I think due to not having correct HTML (maybe) it doesn't work.
fileButton.addEventListener('change', function(e){
//Get files
for (var i = 0; i < e.target.files.length; i++) {
var imageFile = e.target.files[i];
uploadImageAsPromise(imageFile);
}
});
//Handle waiting to upload each file using promise
function uploadImageAsPromise (imageFile) {
return new Promise(function (resolve, reject) {
var storageRef = firebase.storage().ref(fullDirectory+"/"+imageFile.name);
//Upload file
var task = storageRef.put(imageFile);
//Update progress bar
task.on('state_changed',
function progress(snapshot){
var percentage = snapshot.bytesTransferred / snapshot.totalBytes * 100;
uploader.value = percentage;
},
function error(err){
},
function complete(){
var downloadURL = task.snapshot.downloadURL;
}
);
});
}
<button type="button" id="fileButton">Upload</button>
<input id="imageFile" type="file" accept="image/*" multiple>
You can try and add console.log statements into your code and check if functions are being called. That helps a little.
Alright, so what I did here I was following this link. Basically, you listen to changes on your image input and push these files into an array. Then, when you submit the form, you have the array ready to be sent to firebase.
The snippet below is working fine :)
const fileCatcher = document.getElementById("fileCatcher");
const fileInput = document.getElementById("fileInput");
let fileList = [];
fileInput.addEventListener('change', function(e){
console.log('Input has changed');
fileList = []; //Reset the list
const files = fileInput.files;
for (var i = 0; i < files.length; i++) {
fileList.push(files[i]);
}
});
fileCatcher.addEventListener('submit', function(e){
e.preventDefault(); //Block the form from reloading the page
console.log(fileList);
const files = fileInput.files.list;
for (var i = 0; i < fileList.length; i++) {
var imageFile = fileList[i];
//uploadImageAsPromise(imageFile);
}
});
<form id = "fileCatcher">
<button type="submit">Upload</button>
<input id="fileInput" type="file" accept="image/*" multiple>
</form>
I am trying to upload multiple images. So I read that I can generate a temporary url and send them with ajax.
The idea is push the url created with filereader into an array and the send with ajax but the url's are not pushed properly. When I see the result I got like an empty array:
But if I click the arrow I can see the url's inside
But them seems Inaccessible.
This is my code:
$('form').on('submit',function(e) {
e.preventDefault();
var filesToUpload = document.getElementById("myFile");
var files = filesToUpload.files;
var fd = new FormData();
var arr = [];
if (FileReader && files && files.length) {
for (i=0; i< files.length; i++){
(function(file) {
var name = file.name;
var fr = new FileReader();
fr.onload = function () {
arr.push(fr.result);
}
fr.readAsDataURL(file);
})(files[i]);
}
console.log(arr);
}
});
The final idea is convert to string JSON.stringify(arr) and then parse in php json_decode($_POST['arr']).
Of course this is not working because JSON.stringify(arr) gets empty.
Maybe the following simple solution works for you? I placed your console.log() and your ajax call into the fr.onload() method but fire it only, after your results array has been filled up with all values:
$('form').on('submit',function(e) {
e.preventDefault();
var filesToUpload = document.getElementById("myFile");
var files = filesToUpload.files;
var fd = new FormData();
var arr = [];
if (FileReader && files && files.length) {
for (var i=0; i< files.length; i++){
(function(file) {
var name = file.name;
var fr = new FileReader();
fr.onload = function () {
arr.push(fr.result);
if(arr.length==files.length) {
console.log(arr);
// place your ajax call here!
}
}
fr.readAsDataURL(file);
})(files[i]);
}
}
});
I'm using HTML5 and JavaScript for reading a text file, but now I need to read exactly 2 text files and do the same operations as done before but for the two files.
For the second file I've been trying with: var file2 = files[1]; and add a multiplein the html input, but how can I do it for the reader.onload = function (e) { part? I want to parse the two files in the same way, not only one.
Here is the code (simplified):
<!DOCTYPE html>
<html>
<head>
<title>Read and Parse Lynis Log</title>
<script>
function processFiles(files) {
var file = files[0];
var reader = new FileReader();
var textParsed = [];
reader.onload = function (e) {
var output = document.getElementById("fileOutput");
output.textContent = e.target.result;
var text = e.target.result;
var lines = text.split("\n");
for (var i= 0; i < lines.length; i++) {
textParsed[i] = lines[i];
}
var testsPerformed = null;
var suggestions = [];
var suggestion = null;
var auxSug = null;
for (var j = 0; j < lines.length; j++) {
if (textParsed[j].includes("tests_executed")){
testsPerformed = textParsed[j];
}
if (textParsed[j].includes("suggestion[]")) {
suggestion = textParsed[j];
suggestions.push(suggestion);
}
}
if (typeof(Storage) !== "undefined" && textParsed.length >= 1) {
//Store
localStorage.setItem('storedText', textParsed);
localStorage.setItem('tests', testsPerformed);
localStorage.setItem('suggestions', suggestions);
}
};
reader.readAsText(file);
}
</script>
</head>
<body>
<input id="fileInput" placeholder=":input" type="file" size="50" onchange="processFiles(this.files)">
<div id="fileOutput"></div>
</body>
</html>
You only need to initialize a FileReader for each file and start readAsText for every file. The function will be the same, I've modify the output so the content is not cleared with each file that is loaded.
<!DOCTYPE html>
<html>
<head>
<title>Read and Parse Lynis Log</title>
<script>
function processFiles(files) {
var file = files[0];
var textParsed = [];
function onReadAsText(e) {
var output = document.getElementById("fileOutput");
output.textContent = output.textContent + e.target.result;
var text = e.target.result;
var lines = text.split("\n");
for (var i= 0; i < lines.length; i++) {
textParsed[i] = lines[i];
}
var testsPerformed = null;
var suggestions = [];
var suggestion = null;
var auxSug = null;
for (var j = 0; j < lines.length; j++) {
if (textParsed[j].includes("tests_executed")){
testsPerformed = textParsed[j];
}
if (textParsed[j].includes("suggestion[]")) {
suggestion = textParsed[j];
suggestions.push(suggestion);
}
}
if (typeof(Storage) !== "undefined" && textParsed.length >= 1) {
//Store
localStorage.setItem('storedText', textParsed);
localStorage.setItem('tests', testsPerformed);
localStorage.setItem('suggestions', suggestions);
}
};
for (var i = 0; i < files.length; i++){
var reader = new FileReader();
reader.onload = onReadAsText;
reader.readAsText(files[i]);
}
}
</script>
</head>
<body>
<input id="fileInput" placeholder=":input" type="file" size="50" onchange="processFiles(this.files)" multiple>
<div id="fileOutput"></div>
</body>
</html>
I have posted code below and trying to upload text files:
Problem is to store data in JavaScript array, ifileData always returns blank/null values.
<input type="file" name="ic-files[]" class="ic-input" multiple="true" />
<input type="file" name="ic-files[]" class="ic-input" multiple="true" />
<input type="file" name="ic-files[]" class="ic-input" multiple="true" />
<input type="file" name="ic-files[]" class="ic-input" multiple="true" />
<script>
var ifileData = new Array();
$(document).on('click','#start', function()
{
$('.ic-input').each(function()
{
if($(this).val() != "")
{
var inCorrectFile = $(this).get(0).files;
for (var i = 0; i < inCorrectFile.length; i++)
{
var reader = new FileReader();
reader.onload = function(e)
{
/* Temp Object */
var ipfileData = {};
var fileContent = this.result;
ipfileData['data'] = fileContent;
ifileData.push(ipfileData);
}
reader.readAsText(inCorrectFile[i], "UTF-8");
}
}
});
alert(JSON.stringify(ifileData));
});
</script>
also i've posted code to https://jsfiddle.net/3aexs7wp/3/
Try substituting change event for click event ; adjusting delegated selector to .ic-input
var ifileData = new Array();
$(document).on('change', '.ic-input', function() {
$('.ic-input').each(function() {
if ($(this).val() != "") {
var inCorrectFile = $(this).get(0).files;
for (var i = 0; i < inCorrectFile.length; i++) {
var reader = new FileReader();
reader.onload = function(e) {
/* Temp Object */
var ipfileData = {};
var fileContent = this.result;
ipfileData['data'] = fileContent;
ifileData.push(ipfileData);
console.log(ifileData)
}
reader.readAsText(inCorrectFile[i], "UTF-8");
}
}
});
// alert(JSON.stringify(ifileData));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="file" name="ic-files[]" class="ic-input" multiple="true" />
jsfiddle https://jsfiddle.net/3aexs7wp/4/
Hi guys how can i convert a image to object in this code for example:
var img = $('<img id="dynamic">');
img.attr('src', 'http://macreationdentreprise.fr/wp-content/uploads/2012/06/ouvrir-un-restaurant.jpeg');
var obj=img.ConvertToObject();
// so i can now use obj.filename; and obj.data;
The reason to do that is if i wan't to upload this image automatically if the input file isn't set:
<input id="picture_zone_upload_input_ID" type="file" name="picture_zone_upload_input" class="picture_zone_upload_input" multiple title="Choose a file to upload"/>
EDIT
function configure_zone_upload() {
$("#picture_zone_upload_input_ID").change(function (event) {
$.each(event.target.files, function (index, file) {
var reader = new FileReader();
reader.onload = function (event) {
object = {};
object.filename = file.name;
object.data = event.target.result;
//alert("index: " + index);
upload_img_count++;
configure_upload_img(object.data, upload_img_count);
files.push(object);
};
reader.readAsDataURL(file);
});
var files = event.target.files;
for (var x = 0; x < files.length; x++) {
data.append(x, files[x]);
}
//alert(files.length);
AJAX_upload_Profile(data, upload_img_count);
});
}
If there isn't a input file how can i set the my default image to send it with ajax ??
EDIT2
If event.target.files; is null how can i set file from new image:
var files = event.target.files;
for (var x = 0; x < files.length; x++) {
data.append(x, files[x]);
}
//alert(files.length);
AJAX_upload_Profile(data, upload_img_count);
I guess you can do this:
object.filename = file.name || defaultImg;
where defaultImg is a variable which contains a default img with src.
somthing like:
reader.onload = function (event) {
object = {};
object.defaultImg = $('<img>',{"src" : "defaultImg/path/img.jpeg"}); // <--declare here
object.filename = file.name
object.data = event.target.result || object.defaultImg; //<---use it here;
//alert("index: " + index);
upload_img_count++;
configure_upload_img(object.data, upload_img_count);
files.push(object);
};