jQuery 获取具有 "multiple" 属性的文件输入的假路径以预览图像

jQuery get fakepath for file input with "multiple" attribute to preview image

我有输入文件(多个)用于上传图像。上传图像时,它将显示为缩略图和完整视图。我已经有 URL.createObjectURL() 将图像渲染为 blob 但是当图像数量更多时它会对页面产生一点影响,因为每个图像都有 2 个 blob 数据用于缩略图和完整视图。

对于单个文件上传,很容易为缩略图设置 URL.createObjectURL() 并为完整视图生成假路径 $(this).val()。但是我不知道如何使用多文件上传。

示例代码:

$('#imageBtn').on('change', function(){
    var inputFiles = this.files;
    $(inputFiles).each(function(index) {
       var reader = new FileReader();
       reader.readAsDataURL(inputFile);
       reader.onloadend = function(){
           RenderedPath = URL.createObjectURL(inputFile);
           FakePath = inputFile.val();
           // Some codes to populate the thumbnail and fullview
       }
    });
});

那么,如何获取每张上传图片的假路径?

我不明白你想用这个 fakePath 做什么。作为“fake”路径,它没有用。

历史上,(在文件 API 之前),这是一种检索选定文件名称的方法,但现在我们已经有了 File API,此信息在内部提供直接文件对象。

所以如果你真的想自己构建它,比如在 input[type=file][multiple] 的情况下,那么你可以简单地将 "C:\fakePath\" 添加到文件的 name.

但再一次,您将无法对此字符串执行任何操作。

另请注意,在您的代码中您没有对 FileReader 的结果做任何事情,无论如何,此时您不需要它,因此请在此处删除它,因为它可能是您的原因之一内存问题。
实际上,对于用户提供的文件,BlobURI 不会使用任何内存,只是指向存储在用户磁盘上的文件的简单指针,而将其作为 dataURI 读取实际上会将整个数据加载到内存中三次。

所以对于你展示的部分,它可以简单地是

$('input[type="file"]').on('change', function() {
  var files = this.files;
  $(files).each(function(index, file) {
    // Still don't know why you want this...
    var fakepath = 'C:\fakepath\';
    $('body').append('<div>' +
      // build  a fake path string for each File
      '<p class="path">'+ fakepath + file.name + '</p>' +
      // all that is really needed to display the image
      '<img src="'+URL.createObjectURL(file)+'">' +
     '</div>');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" multiple>

现在,如果您在谈论 this one, then you've to know that it accepts Blobs,您在评论中声明您需要 FileReader 将其传递给 jsZip 库。所以你仍然不需要 FileReader。

var fileList = [];
$('input[type="file"]').on('change', function() {
  var files = this.files;
  $(files).each(function(index, file) {
    $('body').append($('<img>', {
      src: URL.createObjectURL(file),
      onload: function() { fileList.push(file); $('button').attr('disabled', false);},
      onerror: function() { $(this).remove(); }
    }));
  });
});

$('button').on('click', function() {
  var zip = new JSZip();
  fileList.forEach(function(file) {
    zip.file(file.name, file);
  });
  zip.generateAsync({
      type: "blob"
    })
    .then(function(blob) {
      saveAs(blob, "myfiles.zip");
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.5/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>

<input type="file" multiple accept="image/*">
<button disabled>save as zip</button>