本文介绍了如何在上传之前预览多个图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含四张图片的页面供用户选择。我希望用户能够在上传之前预览网站上的每个图片。
I have a page with four images for the user to select. I want the user to be able to preview each image on the site before upload.
下面的JavaScript代码仅适用于一个图片,但我希望它适用于多个图片通过< input type =file>
。
The JavaScript code below works for only one image but I would like it to work for multiple images uploaded via <input type="file">
.
上传图片的最佳方式是什么这个?
What will be the best way to do this?
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#output').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#file-input").change(function () {
readURL(this);
});
推荐答案
这里是 jQuery 版本为你。我认为这更简单。
Here is jQuery version for you. I think it more simplest thing.
$(function() {
// Multiple images preview in browser
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#gallery-photo-add').on('change', function() {
imagesPreview(this, 'div.gallery');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" multiple id="gallery-photo-add">
<div class="gallery"></div>
这篇关于如何在上传之前预览多个图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!