问题
Background: I have a django project where a user can upload multiple images, and one of them will be the main image. I am using Filepond to upload and optimize images.
The order that Filepond uploads files is not always the same as the order of files selected by a user. Because of that, I try to provide an option for user where a user clicks on a file (in this case, showed as a preview image) and the clicked file will become the main image.
I used the following code to log user-clicked image as the main image in the server-side and it works.
onactivatefile: (file) => {
filename = file.filename;
$.ajax({
type: "POST",
url: "{% url 'ajax_mainimage' pk=sellingitem.pk %}",
data: {pk:"{{sellingitem.pk}}", 'filename':filename, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
dataType: "json",
});
},
Question: To provide a better experience for the user, I try to achieve the following: when a user clicks one of the preview images, say image A, a text ("this is your main image") or an icon shows up in the image A. How can I do this or something similar? Thanks!
EDIT
I used the following code to workaround this problem temporarily, but it's not optimal. Basically, I generated a thumbnail of the clicked image to show the user.
onactivatefile: (file) => {
filename = file.filename;
// get the div that will contain mainimage
const img = document.getElementById('insert_mainimage')
// set src of img
img.src = '../../media/post_images/' + {{sellingitem.pk}} +'/' + filename;
$.ajax({
type: "POST",
url: "{% url 'ajax_mainimage' pk=sellingitem.pk %}",
data: {pk:"{{sellingitem.pk}}", 'filename':filename, 'csrfmiddlewaretoken': '{{ csrf_token }}'},
dataType: "json",
});
},
Still seeking help: What i really want is that after clicking the image (rendered by filepond image preview plugin), an icon/text will show up on that particular image. Or, an icon will show up on each uploaded image, once clicked, the icon changes somehow to indicate that this image has been chosen to be the main image.
回答1:
I'm working on the same job.
Try to this code
onactivatefile={(e) => {
const getEl = document.querySelectorAll('.filepond--file-info-main');
for (let i = 0; i < getEl.length; i++) {
if(getEl[i].innerText === e.file.name){
getEl[i].style.backgroundColor = "red";
}else{
getEl[i].removeAttribute("style");
}
}
}}
来源:https://stackoverflow.com/questions/58793579/add-an-icon-div-to-the-preview-images-when-onactivatefile-is-fired-filepond