如何在div中提交表单之前使用jquery显示上传图像预览

我正在处理一个包含各种表单元素的表单,可以选择上传多个图像(最多6个)。 现在我正在点击该div的div preview我使用jquery获取所有表单字段(此时表单仍未提交,因为它是一个多表单step1,2和3)。 现在问题是我使用此代码获取所有表单数据 –

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

使用这个另一个代码,我能够显示div中的其余数据,但图像不会出现。

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

这是JS创建的上传图像的字段。

  var total_images = 1 ; function add_file_field () { total_images++ ; if ( total_images > 6 ) return ; var str_to_embed = '
' ; $("#image_stack").append ( str_to_embed ) ; }

所有事情都在单页上进行,所以我需要一个解决方案,如何在我的预览div下加载图像。 让我知道如果thr仍然存在一些歧义点。

您需要从多个输入循环遍历文件数组,并在每个输入上使用FileReader API。

我已经设置了这样的HTML:

   
​​​​​​​​​​​​​​​​​​​​​​

那么javascript如下:

 // 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 = $('').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(); }); 

我已经建立了一个JSFiddle来演示http://jsfiddle.net/3LB72/

您可能希望对用户使用的浏览器是否具有FileReader以及他们选择的文件是否为图像文件进行更多检查。

JSFiddle演示

这更好,没有点击任何按钮:D

HTML:

   

JavaScript的:

 // 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 $("#images").css({'background-image':'url('+e.target.result+')'}); // if there are more files run the file reader again if (i < numFiles) { i++; readFile(); } }; $('#files').live('change', function(){ imageFiles = document.getElementById('files').files // get the number of files numFiles = imageFiles.length; readFile(); });