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>
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>
)
}
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>
Delete image preview before upload
Multiple input type file return a read-only fileList
. It contains a collection of File
objects. Therefore u can't simply remove an element from this list.
You have to use AJAX to handling the Form. Referthis question.
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>
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>
Related Topics
Nesting Quotes in JavaScript/Html
Why Does a Form with One Text Input Submit on Enter While One with Two Text Inputs Does Not
Why Is the Variable Holding the Input Value Always Logged as Empty
Uncaught Referenceerror: $ Is Not Defined Error in Jquery
Fade Background Image in and Out with Jquery
How to Use Jquery in Chrome Extension
How to Stop Event Bubbling on Checkbox Click
Ecmascript 6 Features Available in Node.Js 0.12
How to Get the Status Code from an Http Error in Axios
What Is "Function*" in JavaScript
Add St, Nd, Rd and Th (Ordinal) Suffix to a Number
Closing Websocket Correctly (Html5, JavaScript)
Remove Leading Zeros from a Number in JavaScript
Correct Use of Arrow Functions in React
Encrypt in PHP Openssl and Decrypt in JavaScript Cryptojs