How to Upload Preview Image Before Upload Through JavaScript

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 upload preview image before upload through JavaScript

For Firefox. Because of security it has a truncated path. However, they have provided other ways of doing this:

var img = document.createElement("IMG");
if(document.all)
img.src = document.getElementById('submit').value;
else
// Your solution for Firefox.
img.src = document.getElementById('submit').files.item(0).getAsDataURL();
document.getElementById('div').appendChild(img);

The below is working in Internet Explorer 7 and Firefox 3.

<style type="text/css">
#prevImage {
border: 8px solid #ccc;
width: 300px;
height: 200px;
}
</style>
<script type="text/javascript">
function setImage(file) {
if(document.all)
document.getElementById('prevImage').src = file.value;
else
document.getElementById('prevImage').src = file.files.item(0).getAsDataURL();
if(document.getElementById('prevImage').src.length > 0)
document.getElementById('prevImage').style.display = 'block';
}
</script>
<pre>
IE8 needs a security settings change: internet settings, security, custom level :

[] Include local directory path when uploading files to a server
( ) Disable
(o) Enable
</pre>
<form>
<input type="file" name="myImage" onchange="setImage(this);" />
</form>
<img id="prevImage" style="display:none;" />

Documentation of File List object on MDC

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>

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>
)
}


Related Topics



Leave a reply



Submit