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 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>
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>
)
}
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>
Related Topics
Creating Multiline Strings in JavaScript
Error: Can't Set Headers After They Are Sent to the Client
What Is the Reason to Use the 'New' Keyword At Derived.Prototype = New Base
Listening For Variable Changes in JavaScript
Do You Recommend Using Semicolons After Every Statement in JavaScript
How to Detect If Multiple Keys Are Pressed At Once Using JavaScript
Difference Between Object Keys With Quotes and Without Quotes
Reactjs Component Names Must Begin With Capital Letters
What Is Event Bubbling and Capturing
Setting "Checked" For a Checkbox With Jquery
Sorting in JavaScript: Shouldn't Returning a Boolean Be Enough For a Comparison Function
How to Get Image Size (Height & Width) Using JavaScript
How to Use Formdata For Ajax File Upload
Location of Parenthesis For Auto-Executing Anonymous JavaScript Functions