上传前显示图像预览时出错

时间:2018-05-07 11:26:07

标签: javascript html twitter-bootstrap-3 upload

我使用以下代码从多个输入上传图像并显示预览。我只能查看第一个输入的预览。当谈到其他三个时,它不起作用。

SCRIPT

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function (e) {
      $('#blah')
      .attr('src', e.target.result);
    };
    reader.readAsDataURL(input.files[0]);
  }
}

HTML

<input type='file' onchange="readURL(this);" />
<img id="blah" src="http://placehold.it/180" alt="your image" />
<input type='file' onchange="readURL(this);" />
<img id="blah2" src="http://placehold.it/180" alt="your image" />
<input type='file' onchange="readURL(this);" />
<img id="blah3" src="http://placehold.it/180" alt="your image" />
<input type='file' onchange="readURL(this);" />
<img id="blah4" src="http://placehold.it/180" alt="your image" />

注意:是否有办法在不更改HTML的情况下,并在脚本中进行一些小改动以显示预览。

我正在使用Bootstrap v3.3

2 个答案:

答案 0 :(得分:1)

实际问题是您使用

$('#blah')

所以每次只更新一个图像标签时,你需要相应地定位diff img标签,其中一种方法是

<强> HTML

<input type='file' onchange="readURL(this, 'blah');" />
 <img id="blah" src="http://placehold.it/180" alt="your image" />
 <input type='file' onchange="readURL(this, 'blah2');" />
 <img id="blah2" src="http://placehold.it/180" alt="your image" />
 <input type='file' onchange="readURL(this, 'blah3');" />
 <img id="blah3" src="http://placehold.it/180" alt="your image" />
  <input type='file' onchange="readURL(this, 'blah4');" />
  <img id="blah4" src="http://placehold.it/180" alt="your image" />

现在你得到img标签的diff id,现在你的js函数看起来像。

<强> JS

function readURL(input, target) {
 if (input.files && input.files[0]) {
 var reader = new FileReader();
 reader.onload = function (e) {
 $('#'+ target)
     .attr('src', e.target.result);
        };
         reader.readAsDataURL(input.files[0]);
        }
        }

现在它有效,祝你好运

答案 1 :(得分:1)

以下是您无需更改HTML即可执行的操作。使用nextElementSibling,您可以获取下一个元素并为其分配src值。

Alternetive与jQuery的.next()函数具有相同的功能。

$(input).next().attr('src', url);

我还建议使用Object urls而不是将文件读取为dataURL,这需要时间在base64编码的字符串之间来回编译和反编译,其中对象url只是指向文件的指针。

function readURL(input) {
  if (input.files && input.files[0]) {
    var url = URL.createObjectURL(input.files[0]);
    input.nextElementSibling.src = url;
    // $(input).next().attr('src', url);
  }
}

如果可以的话,可以在文件输入accept="image/*"中添加一个额外的属性,这样他们只会选择一个有效的图像文件

相关问题