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>
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>
How to preview/display an image after uploading at the side of the upload button in Vue.js (Element.ui)?
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 your input type='file'
to listen to the change event and then access the image uploaded by event.target.files[0]
. Then change the src
of the img
tag with the uploaded image src
.
Live Demo Here
You can also send it to server immediately after uploading it in the preview()
method or you can use upload
button to send it to the server.
Your Vue Template:
<template>
<div id="app">
<img id="image" :src="imgSrc" />
<input type=file @change="preview">
<div>
<button @click="upload()">Upload</button>
</div>
<div> {{ uploaded }} </div>
</div>
</template>
Script:
data: () => ({
imgSrc: '',
uploaded: ''
}),
methods: {
preview(e) {
var pic = document.getElementById('image')
let imgSrc = URL.createObjectURL(e.target.files[0]);
this.imgSrc = imgSrc
},
upload() {
this.uploaded = this.imgSrc;
}
}
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 preview an image before and after upload?
Try this: (For Preview)
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
<body>
<form id="form1" runat="server">
<input type="file" onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
</form>
</body>
Working Demo here>
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>
)
}
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>
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>
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
Integrating Mailjet API V3 Wrapper as Codeigniter Library
Getting the First Character of a String with $Str[0]
Symfony 2 Entitymanager Injection in Service
Convert Jpg/Gif Image to Png in PHP
Php: Settings Memory_Limits > 1024M Does Not Work
How to Decrypt a Password Hash in PHP
Apache Mod Rewrite for Laravel
Mysqli Binding Params Using Call_User_Func_Array
Check If a Row Exists Using Old MySQL_* API
Like Query Using Multiple Keywords from Search Field Using Pdo Prepared Statement
How to Specify Composer Install Path
How to Force Laravel Project to Use Https for All Routes
Test If Port Open and Forwarded Using PHP
HTML Upload Max_File_Size Does Not Appear to Work
How to Remove "Via" and Server Name When Sending Mails with PHP