上传文件并显示在同一页面

yan*_*yan 3 html jquery

HTML:

<input name="fileToUpload" type="file" id="fileToUpload"/>
<div id="div1"> </div>
Run Code Online (Sandbox Code Playgroud)

查询:

$(function()
{
   $("#fileToUpload").on('change', 'input' ,  function(){
   // Display image on the page for viewing
        readURL(this,"div1");

   });
});

function readURL(input , tar) {  
if (input.files && input.files[0]) { // got sth

    // Clear image container
    $("#" + tar ).empty(); 

    $.each(input.files , function(index,ff)  // loop each image 
    {

        var reader = new FileReader();

        // Put image in created image tags
        reader.onload = function (e) {
            $('#' + tar).attr('src', e.target.result);
        }
        reader.readAsDataURL(ff);

    });
}   
Run Code Online (Sandbox Code Playgroud)

我想显示上传到 div 容器的图像,但是我的代码不起作用。知道如何使它工作吗?

Jon*_*nny 5

问题是,你是

  1. 试图在 div 上设置 src 属性
  2. 错误地使用 on() 的第二个参数(它是一个选择器字符串,用于过滤触发事件的选定元素后代

$("#fileToUpload").on('change', 'input' , function(){

变成

$("#fileToUpload").on('change', function(){

你的 div 变成了一个 img。

完整解决方案:

<input name="fileToUpload" type="file" id="fileToUpload"/>
<img id="preview" />
Run Code Online (Sandbox Code Playgroud)
$(function() {
  $("#fileToUpload").on('change', function() {
    // Display image on the page for viewing
    readURL(this, "preview");

  });
});

function readURL(input, tar) {
  if (input.files && input.files[0]) { // got sth

    // Clear image container
    $("#" + tar).removeAttr('src');

    $.each(input.files, function(index, ff) // loop each image 
      {

        var reader = new FileReader();

        // Put image in created image tags
        reader.onload = function(e) {
          $('#' + tar).attr('src', e.target.result);
        }

        reader.readAsDataURL(ff);

      });
  }
}
Run Code Online (Sandbox Code Playgroud)

工作小提琴:https : //jsfiddle.net/u7ww6bwv/