我有输入文件(多个)用于上传图像。上传图像后,它将显示为缩略图和完整 View 。我已经有 URL.createObjectURL()
将图像渲染为 blob
但当图像数量较多时,它会对页面产生一点影响,因为每个图像都有 2 个用于缩略图和完整 View 的 blob 数据。
对于单个文件上传,很容易使用 URL.createObjectURL()
生成缩略图,使用 $(this).val()
生成完整 View 的假路径。但我不知道如何通过多文件上传来做到这一点。
示例代码:
$('#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 做什么。作为一个“假”路径,它是没有用的。
从历史上看,(在文件 API 之前),这是一种检索所选文件名称的方法,但现在我们已经得到了 File API ,此信息直接在 File 对象内部提供。
因此,如果您确实想自己构建它,就像 input[type=file][multiple]
的情况一样,那么您只需在前面添加 "C:\fakePath\"
到文件的名称
。
但是,您将无法从此字符串执行任何操作。
另请注意,在您的代码中,您不会对 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,则需要 FileReader 将其传递给 jsZip 库。 ,那么你必须知道it accepts Blobs 。所以你仍然不需要 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>
关于javascript - jQuery 获取具有 "multiple"属性的文件输入的 fakepath 来预览图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49825760/