Vijay Soni
Vijay Soni

Reputation: 207

how to show image just after uploading in django form

I have a model of image and I want that when a user uploads the image field of the model the image should be shown in the form so that user can confirm the uploaded image but I didn't find any easy solution to do this task. Please show me what is the good and easy way to implement this functionality.

Upvotes: 1

Views: 1003

Answers (2)

KAVYA SHARMA
KAVYA SHARMA

Reputation: 104

Well this can be achieved with a very few lines of javascript.

HTML

 <input type="file" accept="image" id="img-input"/>
 <img id="display-img"/>

Javascript

const imgInput = document.querySelector("#img-input")
const displayImg = document.querySelector("#display-img")
displayImg.src = URL.createObjectURL(imgInput.files[0])

Or more practical way is to add event listner on img input ->

const imgInput = document.querySelector("#img-input")
const displayImg = document.querySelector("#display-img")
imgInput.addEventListener('change',(event)=>{
   const imgObject = event.target.files[0]
   displayImg.src = URL.createObjectURL(imgObject)})

And also check this code snippet.

const imgInput = document.querySelector("#img-input")
const displayImg = document.querySelector("#display-img")
imgInput.addEventListener('change',
(event)=>{
   const imgObject = event.target.files[0]
   displayImg.src = URL.createObjectURL(imgObject)})
<input type="file" accept="image" id="img-input"/>
 <img id="display-img"/>

Upvotes: 2

fbzyx
fbzyx

Reputation: 349

css:

#display-image{
  width: 400px;
  height: 225px;
  border: 1px solid black;
  background-position: center;
  background-size: cover;
}

html:

<input type="file" id="image-input" accept="image/jpeg, image/png, image/jpg">

<div id="display-image"></div>

js:

const image_input = document.querySelector("#image-input");
image_input.addEventListener("change", function() {
  const reader = new FileReader();
  reader.addEventListener("load", () => {
    const uploaded_image = reader.result;
    document.querySelector("#display-image").style.backgroundImage = `url(${uploaded_image})`;
  });
  reader.readAsDataURL(this.files[0]);
});

When the input image field changes, the load event get fired. the selected image will be set as the background of the div with id display-image..

Upvotes: 0

Related Questions