Reputation: 37
I am trying to allow users on my site to upload multiple photo and also preview once on change using jQuery, but my problem is that the first file once on change preview and then append a new file input but the one that is appended does not preview once on change.
I don't know the problem I have been trying to figure it out over some hours now but not yet.
$(function(){
$(".append_pre_p_v div input[type=file]").on("change",function(){
var filecount = $(".append_pre_p_v").children("div").length;
//var idnum = filecount + 1;
var filereader = new FileReader();
var img = $(this).siblings("img");
filereader.onloadend = function(){
img.attr("src",this.result).css({"width":"150px","height":"150px"});
};
filereader.readAsDataURL(this.files[0]);
$(this).siblings("label").hide();
var filearray = "<div class='filearray'><img src=' ' ><input type='file' name='file[]' id='file"+idnum+"'> <label for='file"+idnum+"'><img src='mediaimages/francis.jpg' width='150px' height='150px'></label></div>";
$(".append_pre_p_v").append(filearray);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="append_pre_p_v">
<div class="filearray">
<img src="" />
<input type="file" name="file[]" id="f_p_v_up1" />
<label for="f_p_v_up1">
<img src="mediaimages/francis.jpg" width="150px" height="150px" />
</label>
</div>
</div>
Upvotes: 0
Views: 7038
Reputation: 1
jQuery(document).ready(function ($) {
console.log("Loaded Custom JS");
$(function () {
let filesArray = [];
function updateInputField(input, files) {
input.value = "";
const dataTransfer = new DataTransfer();
files.forEach((file) => dataTransfer.items.add(file));
input.files = dataTransfer.files;
}
function displayImages(input, placeToInsertImagePreview) {
const gallery = $(placeToInsertImagePreview);
gallery.empty();
filesArray.forEach((file, index) => {
const reader = new FileReader();
const currentIndex = index;
reader.onload = function (event) {
console.log("index=" + currentIndex);
const wrapper = $("<div>")
.addClass("image-wrapper")
.attr("data-flag", currentIndex);
$("<img>")
.attr("src", event.target.result)
.attr("height", "100px")
.attr("width", "100px")
.appendTo(wrapper);
$("<button>")
.addClass("btn-close")
.text("X")
.on("click", function () {
filesArray.splice(currentIndex, 1);
$(".featured_image_key").val("");
updateInputField(input, filesArray);
displayImages(input, placeToInsertImagePreview);
})
.appendTo(wrapper);
wrapper.appendTo(gallery);
};
reader.readAsDataURL(file);
});
}
$("#gallery-photo-add").on("change", function () {
filesArray = Array.from(this.files);
console.log(filesArray);
if (filesArray.length > 5) {
Swal.fire({
text: "Please Select only 5 images",
title: "Error",
icon: "error",
});
filesArray = [];
this.value = "";
return;
}
displayImages(this, "#gallery");
});
});
$(document).on("click", ".image-wrapper", function () {
$(".image-wrapper").removeClass("addBorder");
$(this).addClass("addBorder");
var flag = $(this).data("flag");
$(".featured_image_key").val("").val(flag);
});
$("#formData").on("submit", function (e) {
e.preventDefault();
console.log("Submitted");
var formData = new FormData(this);
formData.append("action", "create_wc_product");
$.ajax({
url: ajaxObject.ajaxUrl,
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function (response) {
if (response.success) {
$(".alert")
.removeClass("alert-danger")
.addClass("alert-success")
.html("")
.html(response.data.message)
.show();
$("#formData")[0].reset();
$(".gallery").empty();
setTimeout(function () {
window.location.href = "http://localhost/product/shop/";
}, 5000);
} else {
$(".alert")
.removeClass("alert-success")
.addClass("alert-danger")
.html("")
.html(response.data.message);
}
$("html, body").animate({ scrollTop: 0 }, "fast");
},
error: function (xhr, error, status) {
alert("Ajax Error:" + error);
$("#loader").hide();
},
});
});
$("#loader").hide();
$(function () {
var loaderTimeout;
var MIN_LOADER_TIME = 2000;
$(document).ajaxStart(function () {
if (loaderTimeout) {
clearTimeout(loaderTimeout);
}
$("#loader").show();
loaderTimeout = setTimeout(function () {
$("#loader").hide();
}, MIN_LOADER_TIME);
});
$(document).ajaxStop(function () {
$("#loader").hide();
});
$(document).ajaxError(function () {
$("#loader").hide();
});
});
});
.gallery {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.image-wrapper {
position: relative;
display: inline-block;
}
.btn-close {
position: absolute;
top: 0;
right: 0;
background: red;
color: white;
border: none;
cursor: pointer;
}
img {
height: 100px;
width: 100px;
}
.addBorder {
border: 2px solid rgb(14, 177, 227);
}
#loader {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
z-index: 9999;
background: url("//upload.wikimedia.org/wikipedia/commons/thumb/e/e5/Phi_fenomeni.gif/50px-Phi_fenomeni.gif")
50% 50% no-repeat rgb(249, 249, 249);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<div id="loader-container">
<div id="loader">
</div>
</div>
<div class="container w-100">
<div class="row">
<div class="col d-flex justify-content-center align-items-center">
<div class="card shadow-lg w-50 bg-light">
<div class="card-header ">
<h4 class="text-center">Add Product Images</h4>
</div>
<div class="card-body">
<div class="alert my-2"></div>
<form id="formData">
<input type="hidden" class="featured_image_key" name="featured_image_key">
<div class="form-group m-3">
<label for="productImages">Product Images</label>
<input type="file" name="productImages[]" id="gallery-photo-add" class="form-control" placeholder="Select Product Images" multiple>
</div>
<div id="gallery"></div>
<div class=" d-flex justify-content-center align-items-center">
<button type="submit" class="btn btn-outline-primary">Add Product</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
Upvotes: 0
Reputation: 1589
I did not know whether I understand your problem well.When a image was previewed and user adds another image,but the previous image disappeared,right? I made some changes to your code to make the answer more clear.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="append_pre_p_v">
<div class="filearray">
</div>
<input type="file" name="file[]" id="f_p_v_up1" />
</div>
<script>
$(document).on('ready',()=>{
$("#f_p_v_up1").on('change',function(){
var filereader = new FileReader();
var $img=jQuery.parseHTML("<img src=''>");
filereader.onload = function(){
$img[0].src=this.result;
};
filereader.readAsDataURL(this.files[0]);
$(".filearray").append($img);
});
});
</script>
I was wondering why not let user upload multiple file one time.The code below is the multiple input version.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="append_pre_p_v">
<div class="filearray">
</div>
<input type="file" name="file[]" id="f_p_v_up1" multiple />
</div>
<script>
$(document).on('ready',()=>{
$("#f_p_v_up1").on('change',function(){
$(".filearray").empty();//you can remove this code if you want previous user input
for(let i=0;i<this.files.length;++i){
let filereader = new FileReader();
let $img=jQuery.parseHTML("<img src=''>");
filereader.onload = function(){
$img[0].src=this.result;
};
filereader.readAsDataURL(this.files[i]);
$(".filearray").append($img);
}
});
});
</script>
Hope this helps.
Upvotes: 3
Reputation: 272
There are other ways to achieve file previews & uploads. You could use a jQuery plugin, in searching I found one from opoloo on GitHub. I'm sure there are many others.
Or you could use some JavaScript and create a preview function, here's an example from codexworld.com:
function filePreview(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#uploadForm + img').remove();
$('#uploadForm').after('<img src="'+e.target.result+'" width="450" height="300"/>');
}
reader.readAsDataURL(input.files[0]);
}
}
Another option is using a service such as Optizilla or Cloudinary to simplify jQuery file upload (and any manipulation if desired) of files. Cloudinary has open source jQuery libraries to integrate the process with existing jQuery code.
Upvotes: 0