Show an Image Preview Before Upload

Preview an image before it is uploaded

imgInp.onchange = evt => {
const [file] = imgInp.files
if (file) {
blah.src = URL.createObjectURL(file)
}
}
<form runat="server">
<input accept="image/*" type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>

Get image preview before uploading in React

No difference, just read your image when the load event finishes. After the load end event handler just set your state:

getInitialState: function(){
return{file: []}
}

_onChange: function(){
// Assuming only image
var file = this.refs.file.files[0];
var reader = new FileReader();
var url = reader.readAsDataURL(file);

reader.onloadend = function (e) {
this.setState({
imgSrc: [reader.result];
})
}.bind(this);
console.log(url) // Would see a path?
// TODO: concat files
},

render: function(){
return(
<div>
<form>
<input
ref="file"
type="file"
name="user[image]"
multiple="true"
onChange={this_onChange}/>
</form>
{/* Only show first image, for now. */}
<img src={this.state.imgSrc} />
</div>
)
}

Show an image preview before upload

Here's a quick example that makes use of the URL.createObjectURL to render a thumbnail by setting the src attribute of an image tag to a object URL:

The html code:

<input accept="image/*" type="file" id="files" />
<img id="image" />

The JavaScript code:

document.getElementById('files').onchange = function () {
var src = URL.createObjectURL(this.files[0])
document.getElementById('image').src = src
}

The code snippet in the HTML example below filters out images from the user's selection and renders selected files into multiple thumbnail previews:

function handleFileSelect (evt) {
// Loop through the FileList and render image files as thumbnails.
for (const file of evt.target.files) {

// Render thumbnail.
const span = document.createElement('span')
const src = URL.createObjectURL(file)
span.innerHTML =
`<img style="height: 75px; border: 1px solid #000; margin: 5px"` +
`src="${src}" title="${escape(file.name)}">`

document.getElementById('list').insertBefore(span, null)
}
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);
<input type="file" accept="image/*" id="files" multiple />
<output id="list"></output>

How to show image preview before Upload?

You can use URL.createObjectURL() to create a Blob URL of uploaded image.

Adjusted html to <div> as appended parent element instead of <span> element.

At first click at <a> element, if next <div> does not contain <img> append <img> else call .toggle() to display <img>.

At click at .close element, call .toggle() instead of .remove().

You can also include an element, for example, <button>, which when clicked, creates a FormData instance to set all or selected File objects as entries of multipart/form-data to upload to server.

$(document).on('click', '.close', function() {  $(this).siblings("img").toggle();})
document.getElementById("uploadBtn").onchange = function() { document.getElementById("uploadFile").value = this.value;};
document.getElementById('uploadBtn').onchange = uploadOnChange;
function uploadOnChange() { var filename = this.value; var lastIndex = filename.lastIndexOf("\\"); if (lastIndex >= 0) { filename = filename.substring(lastIndex + 1); } var files = $('#uploadBtn')[0].files; for (var i = 0; i < files.length; i++) { (function(i) { $("#upload_prev").append('<div><br><div class="col-md-10"><span class="uploadFiles">' + '<a href="">' + files[i].name + '</a>' + '</span></div><div class="col-md-2"><p class="close" style="font-size: 13pt;">削除</p><br></div></div>'); $("#upload_prev a:contains(" + files[i].name + ")") .on("click", function(e) { e.preventDefault(); var close = $(this).closest("div") .next("div") .find(".close"); if (!$(this).closest("div") .next("div").find("img").length) close .after( $("<img>", { src: URL.createObjectURL(files[i]) }) ) else close.siblings("img").toggle() }) })(i); }
document.getElementById('filename').value = filename;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><input id="uploadBtn" type="file" class="upload" multiple="multiple" accept="image/*" name="browsefile" style="display: none !important;" />
<input type="button" value="ファイル追加" onclick="document.getElementById('uploadBtn').click();" style="float: right;" />
<input id="filename" type="hidden" /><br><div id="upload_prev"></div><div style="clear:both;"></div>

Image preview before upload in angular 5

.html

Update event attr and handler param for input.
And you should use data binding for src attribute. Following will apply src if it's not null or undefined or hardcoded url ('http://placehold.it/180')

<input type='file' (change)="readURL($event);" />
<img id="blah" [src]="imageSrc || 'http://placehold.it/180'" alt="your image" />

.ts

In component ts file (class) you should have property imageSrc which be used in view (html) and your function should be a method of that class

...
imageSrc: string;
...
constructor(...) {...}
...
readURL(event: Event): void {
if (event.target.files && event.target.files[0]) {
const file = event.target.files[0];

const reader = new FileReader();
reader.onload = e => this.imageSrc = reader.result;

reader.readAsDataURL(file);
}
}

Preview an image before it is uploaded VUEjs

Please keep in mind that a browser cannot display all image types, (eg: a tiff won't work with this method).

There's a few steps:

  • Have a file input with a @change listener
  • In the onChange, you create an object URL
  • Use this URL to display the image

const vm = new Vue({  el: '#app',  data() {    return {      url: null,    }  },  methods: {    onFileChange(e) {      const file = e.target.files[0];      this.url = URL.createObjectURL(file);    }  }})
body {  background-color: #e2e2e2;}
#app { padding: 20px;}
#preview { display: flex; justify-content: center; align-items: center;}
#preview img { max-width: 100%; max-height: 500px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script><div id="app">  <input type="file" @change="onFileChange" />
<div id="preview"> <img v-if="url" :src="url" /> </div></div>

Preview images before upload

Here is jQuery version for you. I think it more simplest thing.

$(function() {    // Multiple images preview in browser    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); }
reader.readAsDataURL(input.files[i]); } }
};
$('#gallery-photo-add').on('change', function() { imagesPreview(this, 'div.gallery'); });});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" multiple id="gallery-photo-add"><div class="gallery"></div>

Display the preview image before uploading it to the database

The problem is that you haven't delegated the event handlers for dynamically generated file uploads:

$wrapper.on('change', '.fileupload', function() {
imagesPreview(this, 'div.gallery');
});

const max_fields = 5;
const template = '<div class="col-lg-4 mb-3"><div class="customfileWrap"><div class=" upload_file"><input type="file" name="slider[]" class="fileupload" multiple><span class="excel_upload_icon"></span><p id="file-name"></p><span class="upload_text"> Click here to upload file </span> <div class="gallery"></div></div><a href="#" class="remove_field"> ✖ </a></div></div>';

// Multiple images preview in browser
const imagesPreview = function() {
const input = this;
const $placeToInsertImagePreview = $(this).parent().find('div.gallery');

if (input.files) {
var filesAmount = input.files.length;

for (let i = 0; i < filesAmount; i++) {
var reader = new FileReader();

reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo($placeToInsertImagePreview);
}

reader.readAsDataURL(input.files[i]);
}
}
};


$(function() {

const $wrapper = $(".input_fields_wrap .row");
const $add_button = $(".add_field_button");
let fileUploadCount = 1;

$add_button.click(e => {
e.preventDefault();
if (fileUploadCount < max_fields) {
fileUploadCount++;
$wrapper.append(template);
}
});

$wrapper.on('click', '.remove_field', function(e) {
e.preventDefault();
$(this).closest('.customfileWrap').remove();
fileUploadCount--;
})

$wrapper.on('change', '.fileupload', imagesPreview);

});
.upload_file {
border: 3px dashed #042954;
position: relative;
text-align: center;
padding: 20px;
border-radius: 3px;
background: #f9f9f9;
height: 120px;
}

.upload_file input {
position: absolute;
width: 100%;
height: 100%;
left: 0;
top: 0;
outline: none;
opacity: 0;
cursor: pointer;
}

.remove_field {
position: absolute;
top: -10px;
right: -10px;
color: #fff;
background-color: red;
width: 22px;
height: 22px;
text-align: center;
border-radius: 20px;
}

.upload_file img {
width: 100px;
}

.customfileWrap {
position: relative;
}

.remove_field {
position: absolute;
top: -10px;
right: -10px;
color: #fff;
background-color: red;
width: 22px;
height: 22px;
text-align: center;
border-radius: 20px;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet">

<section>
<div class="container">
<div class="input_fields_wrap">
<button class="add_field_button mb-3">Add More Images</button>
<div class="row">
<div class="col-lg-4 mb-3">
<div class="customfileWrap">
<div class=" upload_file">
<input type="file" name="slider[]" class="fileupload" multiple>
<span class="excel_upload_icon"></span>
<p id="file-name"></p>
<span class="upload_text"> Click here to upload file </span>
<!-- <img id="previewimg1" src="#" alt="Sample Image" class="previewimg" /> -->
<div class="gallery"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>


Related Topics



Leave a reply



Submit