javascript - 在以下场景中,如何使代码适用于多个文件文件对象?

标签 javascript jquery html file-upload jquery-file-upload

我有一个包含四个文件控件的表单。根据用户的选择,它们的数量可能会增加或减少。但至少其中一个将保留在表单上。

我想显示用户为每个文件控件选择上传的图像的图像缩略图。

我能够显示一个文件控件的缩略图,但无法使其适用于表单上的多个文件控件。

HTML表单代码如下:

<form action="add.php" role="form" method="post" enctype="multipart/form-data">
  <img src="http://localhost/prj/img/abc.jpeg" width="80" height="80">
  <input type="file" name="product_image[1]" id="product_image_1">

  <img src="http://localhost/prj/img/def.jpeg" width="80" height="80">
  <input type="file" name="product_image[2]" id="product_image_2">

  <img src="http://localhost/prj/img/lmn.jpeg" width="80" height="80">
  <input type="file" name="product_image[3]" id="product_image_3">

  <img src="http://localhost/prj/img/pqr.jpeg" width="80" height="80">
  <input type="file" name="product_image[4]" id="product_image_4">
  .
  .
  .
  .
  .
  and could be so on
</form>

仅适用于一个文件控件的 jquery 代码如下:

HTML 代码是:

<form id="form1" runat="server">
  <input type='file' id="imgInp" />
  <img id="blah" src="#" alt="your image" width="80" height="80"/>
</form>

jQuery 代码:

$(document).ready(function() {
  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]);
    }
  }

  $("#imgInp").change(function() {
    readURL(this);
  });
});

js Fiddle 链接是: http://jsfiddle.net/LvsYc/

当只有一个这样的文件字段时,上面的代码对我来说工作得非常好。

但是当可能存在多个此类文件控件时,无法使同一功能适用于表单。

有人可以在这方面帮助我吗?

感谢您花费宝贵的时间来理解我的问题。等待您的宝贵回复。

如果您想了解有关我的问题的任何信息,请告诉我。

最佳答案

可能是我的answer对此question将有帮助:

$.fn.checkFileType = function (options) {
var defaults = {
    allowedExtensions: [],
    preview: "",
    success: function () {},
    error: function () {}
};
options = $.extend(defaults, options);
$previews = $(options.preview);
return this.each(function (i) {

    $(this).on('change', function () {
        var value = $(this).val(),
            file = value.toLowerCase(),
            extension = file.substring(file.lastIndexOf('.') + 1),
            $preview = $previews.eq(i);

        if ($.inArray(extension, options.allowedExtensions) == -1) {
            options.error();
            $(this).focus();
        } else {
            if (this.files && this.files[0] && $preview) {
                var reader = new FileReader();
                reader.onload = function (e) {
                    $preview.show().attr('src', e.target.result);
                    options.success();
                };

                reader.readAsDataURL(this.files[0]);
            } else {
                options.error();
            }

        }

    });

  });
};

您可以按如下方式使用上述函数:

$('.fileUpload').checkFileType({ // where fileUpload is the common class given for file upload elements
  allowedExtensions: ['jpg', 'jpeg',"gif"], // allowed extensions
  preview: ".preview", // where .preview is the common class given for file upload elements
  success: function () {
    alert('success')
  },
  error: function () {
    alert('Error');
  }
});

图像将被设置为 src <input> 索引处的元素在 preview 中指定的 jQuery 选择器匹配的元素集中选项。

Demo

关于javascript - 在以下场景中,如何使代码适用于多个文件文件对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25684027/

相关文章:

javascript - 将 byteArray 保存为 Titanium 中的 pdf 文件

jquery-ui - 在 jquery.load() 之后保留 jquery-ui 元素类

javascript - 创建警告框(jQuery、Bootstrap)但它一直消失

html - Bootstrap4 align-items-end 不工作

python - 如何查找 <div > 的特定属性的值

html - CSS 3 列布局

javascript - 如何延迟15分钟? 5分钟限制

javascript - MEAN.JS 无法连接 MongoDB

javascript - 单击按钮时的表单数据

javascript - 将 Javascript 数组发布到 WebAPI