javascript - 在上传替换最后一个图像问题之前上传和预览文件
问题描述
我正在尝试上传图像并一张一张预览它,但它会替换最后一张图像。我想继续添加越来越多的图像,但只有最后一张图像显示在收到的 $_FILES 数组中
保持所有上传图像的形式并保持预览。
我的代码
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" id="add-gallary" name="filecollections[]">
<input type="submit" value="Submit">
<div class="gallery"></div>
</form>
<script>
$(function() {
var upload_count = 0;
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);
}
// input.files.append(input.files[i]);
reader.readAsDataURL(input.files[i]);
upload_count++;
}
}
};
$('#add-gallary').on('change', function() {
imagesPreview(this, 'div.gallery');
});
});
</script>
解决方案
仅上传最后一张图片的原因是您将图片存储在一个文件中,array
因为您有单个文件上传input
。
如果你想上传多张图片,你在表单提交上有预览器,你需要将它们存储在我命名的数组中imagesToUpload
一旦您预览了所有图像并准备提交带有您选择和预览的图像的表单,您就可以forEach
遍历该数组imagesToUpload
并将这些文件数据附加到formData
.
然后,您将这个 formData 到您的后端,并使用ajax
请求将所有图像上传到后端。
运行下面的代码片段以查看该数组正在使用.push
函数来存储您预览的所有图像。
$(function() {
var upload_count = 0;
//Store images in array
var imagesToUpload = []
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);
}
// input.files.append(input.files[i]);
//Push images to array on preview
imagesToUpload.push(input.files[i])
reader.readAsDataURL(input.files[i]);
upload_count++;
}
}
};
$('#add-gallary').on('change', function() {
imagesPreview(this, 'div.gallery');
console.log(imagesToUpload)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" id="add-gallary" name="filecollections[]">
<input type="submit" value="Submit">
<div class="gallery"></div>
</form>
推荐阅读
- java - 嵌套ifs或ands?
- python - Python 多个子正则表达式
- algorithm - 停止后台服务的跨平台方案
- python - 为什么 numpy.save 为 sys.getsizeof 0.33MB 数据生成 100MB 文件?
- ffmpeg - 编码为 h264 无法使用 ffmpeg c api 发送一些帧
- reactjs - 如何使用 react-router 在组件中保存表单的状态
- python - 根据两个条件删除行
- angular - 以角度发布来自 API 的显示数据
- javascript - fetchAll 在 Javascript 中导致“无法读取属性”错误
- c - .c 文件中的静态函数/变量