I am working on displaying/previewing an image after uploading it. I am trying to upload an image and then make an axios/AJAX call.
Please find the code below:
HTML code:
<span>User Name</span>
<input v-model="person_name" placeholder="Edit Me">
<br>
<!--Uploading pic -->
<span>Display Pic</span>
<input type="file" name="file" />
<br>
<!-- I want to display this uploaded pic here, before submitting the form -->
<!-- Skipping the code to submit (button code, etc) the form -->
Javascript Code --> AJAX/FETCH call to the API
var formData = new FormData();
var fileField = document.querySelector("input[type='file']");
formData.append('username', this.person_name);
formData.append('File', fileField.files[0]); // getting the file attached
const body = formData;
const init = {
method: 'POST',
body
};
fetch('http://..xyz....com', init)
.then((response) => {
return response.json(); // or .text() or .blob() ...
})
.then((text) => {
// text is the response body
})
.catch((e) => {
// error in e.message
});
},
How do I display or preview the picture/photo as an avatar or something after uploading the pic.
As far as I understand your question you can preview the uploaded image before sending it to the server. You can attach an
@change
event listener on yourinput type='file'
to listen to the change event and then access the image uploaded byevent.target.files[0]
. Then change thesrc
of theimg
tag with the uploaded imagesrc
.Live Demo Here
You can also send it to server immediately after uploading it in the
preview()
method or you can useupload
button to send it to the server.Your Vue Template:
Script: