Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
53
rated 0 times [  56] [ 3]  / answers: 1 / hits: 22683  / 12 Years ago, wed, may 30, 2012, 12:00:00

I am dealing with a form that contains various form elements with an option to upload multiple images(upto 6 max). Now i am having a div preview on clicking that div i fetch all form fields using jquery (form still not submitted at this time as its a multi form step1, 2 and 3). Now the problem is that i am fetching all form data with this code -



var allFormData = $(#myform).serializeArray(); 


Using this another code i am able to show rest of the data in div, but image is not coming.



$.each(adtitletoshow, function(i, field){
if( field.name == 'desc'){
$(.add_desc).text(field.value);
}
});


This is the filed created by JS to upload image.



<script type=text/javascript>
var total_images = 1 ;
function add_file_field () {
total_images++ ;
if ( total_images > 6 ) return ;
var str_to_embed = '<input name=fileImage[] size=40 style=width: 500px; type=file onChange=add_file_field()><br>' ;
$(#image_stack).append ( str_to_embed ) ;
}
</script>


All things going on single page so i need a solution that how can i load images under my preview div. Let me know if thr is some point of ambiguity still persists.


More From » php

 Answers
58

You need to loop through the files array from the multiple input and use the FileReader API on each.



I've set up the HTML like this:



​<input type=file multiple=true id=files />
<input type=submit id=go/>
<div id=images></div>​​​​​​​​​​​​​​​​​​​​​​


Then the javascript as follows:



// set up variables
var reader = new FileReader(),
i=0,
numFiles = 0,
imageFiles;

// use the FileReader to read image i
function readFile() {
reader.readAsDataURL(imageFiles[i])
}

// define function to be run when the File
// reader has finished reading the file
reader.onloadend = function(e) {

// make an image and append it to the div
var image = $('<img>').attr('src', e.target.result);
$(image).appendTo('#images');

// if there are more files run the file reader again
if (i < numFiles) {
i++;
readFile();
}
};

$('#go').click(function() {

imageFiles = document.getElementById('files').files
// get the number of files
numFiles = imageFiles.length;
readFile();

});


I've set up a JSFiddle to demo http://jsfiddle.net/3LB72/



You'll probably want to do more checks on whether the browser the user is using has FileReader and if the files they have chosen are image files.


[#85262] Tuesday, May 29, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
yulissamirandah

Total Points: 493
Total Questions: 115
Total Answers: 94

Location: Lebanon
Member since Sun, Aug 2, 2020
4 Years ago
yulissamirandah questions
Fri, Jun 17, 22, 00:00, 2 Years ago
Wed, Aug 26, 20, 00:00, 4 Years ago
Tue, Jan 28, 20, 00:00, 4 Years ago
Mon, Nov 11, 19, 00:00, 5 Years ago
;