Show photo preview uploaded via html form - javascript

I have a form that allows users to upload x amount of image. When they choose the images from their computer, there is a button that they can click, which allows them to preview the images before submitting the form.
Is there a way to show the images automatically without having to click a Preview button. At the moment, I am using the JS .click function, but I would rather that users didn't have to click anything to see what images they uploaded.
Here is the code I am using.
In the form:
<div class="uploadWrapper">
<p>Upload Images</p>
<input type="file" name="files[]" multiple="true" id="files" style="left: 0px;" />
</div>
<input id="go" class="btn_img" type="button" value="Click to Preview Images">
<div id="images_upload"></div>
<script type="text/javascript">
$("#files").click(function(){
$(".btn_img").show();
});
</script>
<?php include_once('upload/image-preview.php'); ?>
The image-preview.php file:
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#up_image').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#file").change(function(){
readURL(this);
});
var reader = new FileReader(),
i=0,
numFiles = 0,
imageFiles;
function readFile() {
reader.readAsDataURL(imageFiles[i])
}
reader.onloadend = function(e) {
var image = $('<img class="prev_img">').attr('src', e.target.result);
$(image).appendTo('#images_upload');
$( "#images_upload img" ).wrap( "<div class=\"an_image\">" );
if (i < numFiles) {
i++;
readFile();
}
};
$('#go').click(function() {
imageFiles = document.getElementById('files').files
numFiles = imageFiles.length;
readFile();
});
</script>
What would I need to do to not have to click the 'Click to Preview Images' button to see the images?
Thanks!

Loop through the input.files and create a new FileReader() for each file. jsFiddle Demo
HTML
<input type='file' class="imageUpload" multiple="true" />
<div class="imageOutput"></div>
JS
$images = $('.images');
$(".imageUpload").change(function(){
readURL(this);
});
function readURL(input) {
if (input.files && input.files[0]) {
$.each(input.files, function() {
var reader = new FileReader();
reader.onload = function (e) {
$images.append('<img src="'+ e.target.result+'" />')
}
reader.readAsDataURL(this);
});
}
}

Thanks #Brian
This is what I came up with. The limit is 10.
$images = $('#images_upload')
$(".imageUpload").change(function(event){
readURL(this);
});
function readURL(input) {
if (input.files[10]) {
alert('You can uploaded a maximum of 10 images');
} else {
if (input.files && input.files[0]) {
$.each(input.files, function() {
var reader = new FileReader();
reader.onload = function (e) {
$images.append('<img src="'+ e.target.result+'" />')
}
reader.readAsDataURL(this);
});
}
}
}

Related

Upload file to an IIS server with AJAX using HTML and JavaScript

I want to be able to upload an image file (.png, .jpg, etc..) to my web-server (running IIS Server with ASPX) using nothing but HTML and AJAX.
Here's the code:
<form id="personal-details-form" name="detailsfrm" method="POST" action="/ASPX/verifyPersonalDetails" enctype="multipart/form-data" novalidate>
<label for="profile-pic-input">
<img id="profile-pic" name="profilepic" class="profile-pic" src="/Media/user.png" onerror="document.profilepic.src = '/Media/user.png'" />
</label>
<img id="profile-pic-check" onerror="clearImage();" style="display: none;"/>
<input id="profile-pic-input" name="pfpinput" type="file" accept="image/png, image/jpeg"
onchange="readImage(this);" style="display: none" />
<!-- more code that has nothing to do with this question...-->
// JS
function readImage(input) {
document.getElementById("personal-details-error").innerHTML = "";
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#profile-pic').attr('src', e.target.result);
$('#profile-pic-check').attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
function clearImage() {
document.getElementById("personal-details-error").innerHTML = "Invalid image.";
document.getElementById("profile-pic-input").value = "";
}
$("#personal-details-form").submit(function (e) {
e.preventDefault();
$(".form-field").addClass("used");
document.getElementById("personal-details-error").innerHTML = ""; // Remove errors
if (document.getElementById("personal-details-form").checkValidity()) {
$.ajax({
type: "POST",
url: "../ASPX/verifyChangeDetails.aspx",
data: $("#personal-details-form").serialize(),
success: function (data) {
},
});
}
});
if (Request.Files["pfpinput"] != null) {
HttpPostedFile MyFile = Request.Files["pfpinput"];
Response.Write(MyFile);
} else {
Response.Write("Nope!");
}
I've heard that enctype="multipart/form-data" works, but clearly doesn't in my case...
What should I do in order for my AJAX code to upload the image file?
Turns out I needed a FormData object, and add a file onto it, along with other things, since I was using AJAX.
var formData = new FormData(document.detailsfrm);
formData.append("pfpinput", document.detailsfrm.pfpinput.files[0]);

How to print the name of the file from JavaScript fileReader?

I am trying to print the name of the uploaded image but it currently just previews the image but not actually printing the name of the file on the html. How can I make it print the name of the file from javascript fileReader function?
Here is my code in the main.js file
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imagePreview').css('background-image', 'url(' + e.target.result + ')');
$('#imagePreview').hide();
$('#imagePreview').fadeIn(650);
}
reader.readAsDataURL(input.files[0]);
}
}
Here is the corresponding html code
<div class="image-section" style="display:none;">
<div class="img-preview">
<div id="imagePreview">
</div>
</div>
In the onload function you can get the file name.
reader.onload = function(e) {
console.log(e.target.fileName);
};
You can access it using name property. So as per your code its:
input.files[0].name

Pass the image file varible from JS function to php function on the same page

In the view, there is a option for upload image with the help of js, now i want pass that image to the php function on the same page. I have tried this code, but i don't know what to do now.
View:
<button type="button" name="userimage" class="profile-user-img img-responsive img-circle"><img class="profile-user-img img-responsive img-circle" src="<?php echo base_url();?>dist/img/user4-128x128.jpg" alt="User profile picture"></button>
<script type="text/javascript">
$("button").click(function(){
var file = new FileModal("image/png");
file.onload = function(d){
console.log(d);
};
file.show();
});
/*The FileModal Class*/
function FileModal(accept){
var callback = function(){};
return {
show: function(){
$("<input>").attr({
type: "file",
accept: accept
}).appendTo("body").hide().change(function(e){
var file = e.target.files[0],
reader = new FileReader();
reader.onload = function(progress){
callback(progress.target.result);
};
reader.readAsDataURL(file);
}).click();
},
set onload(c){ callback = c;
}
}
}
</script>

value not getting stored in a variable

I have created a form where it asks user to upload his/her photo. But i am not able to save encoded value of my image. I want to save this value in a variable. I am not getting why my value is not getting saved in 'result' variable.
<html>
<body>
<input type="file" id="inp"/>
<img id="img" />
<div id="b64"></div>
<script type="text/javascript">
function EL(id) { return document.getElementById(id); }
function readFile() {
if (this.files && this.files[0]) {
var FR= new FileReader();
FR.onload = function(e) {
EL("img").src = e.target.result;
EL("b64").innerHTML = e.target.result;
};
var result = FR.readAsDataURL( this.files[0] );
console.log(result);
}
}
EL("inp").addEventListener("change", readFile, false);
</script>
</body>
</html>
Because event onload runs asynchronously, and you try to access the value synchronously, which result to undefined
move your logic inside onload, or if you want synchronous code style use promises instead.
<html>
<body>
<input type="file" id="inp"/>
<img id="img" />
<div id="b64"></div>
<script type="text/javascript">
function EL(id) { return document.getElementById(id); }
function readFile() {
if (this.files && this.files[0]) {
var FR= new FileReader();
FR.onload = function(e) {
EL("img").src = e.target.result;
EL("b64").innerHTML = e.target.result;
//put your code here
console.log(e.target.result);
};
FR.readAsDataURL( this.files[0] );
}
}
EL("inp").addEventListener("change", readFile, false);
</script>
</body>
</html>

Load image with Filereader API and zip it using JSZip

I'm trying to load an image using fileready api, save it in a newly made zip file made using jszip, with the name logo.png. My problem is getting the image to save in the zip from filereader.
$(document).ready(function() {
$(".load").on("change", function(evt) {
var file = evt.target.files;
var reader = new FileReader();
reader.onload = (function(event) {
return function(e) {
var imgBinary = e.target.result;
var imgz = new Image();
imgz.attr("src", event.target.result);
imgz.attr("width", 128);
imgz.attr("height", 128);
holder.html("");
holder.append(imgz);
};
});
reader.readAsDataURL(file);
// reader.readAsArrayBuffer(file);
// Download Zip
$(".download").on("click", function() {
var zip = new JSZip();
zip.load(webAppZipBinary);
zip.file("Hello.txt", "Hello World\n");
var content = zip.generate({type:"blob"});
// see FileSaver.js
saveAs(content, theFile.name.substr(theFile.name.length - theFile.name.length, theFile.name.length - 4) + "-win.zip");
});
return false;
});
// Trigger Load Image
$(".trigload").click(function() {
$("input").trigger("click");
});
});
#import url("http://necolas.github.io/normalize.css/3.0.1/normalize.css");
.hide {
display: none;
}
.holder {
text-align: center;
}
.fr {
float: right;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="http://stuk.github.io/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="http://stuk.github.io/jszip-utils/dist/jszip-utils.js"></script>
<script type="text/javascript" src="http://stuk.github.io/jszip/vendor/FileSaver.js"></script>
<input type="file" class="hide">
<a class="trigload" href="javascript:void(0)">Load Image</a>
<a class="download fr" href="javascript:void(0)">Download</a>
<div class="holder"></div>
What I changed:
I don't think we can use an ArrayBuffer to preview an image, I now have two Readers: one for the preview, one for JSZip (which performs way better on ArrayBuffer than on strings)
I moved the "download code" after the Reader: we need to read the Blob, add the content to the zip and then prepare the download link. You have other ways to do it, that's just an example.
I added the logo.png in the zip.
I fixed minor errors (missing css class, Image#attr doesn't exist, etc)
function displayPreview(file) {
var reader = new FileReader();
reader.onload = function(e) {
var holder = $(".holder");
var imgUrl = e.target.result;
var imgz = $("<img>");
imgz.attr("src", imgUrl);
imgz.attr("width", 128);
imgz.attr("height", 128);
holder.html("");
holder.append(imgz);
};
reader.readAsDataURL(file);
}
$(document).ready(function() {
$(".load").on("change", function(evt) {
var file = evt.target.files[0];
displayPreview(file);
var reader = new FileReader();
reader.onload = function(e) {
// Download Zip
$(".download").on("click", function() {
var zip = new JSZip();
zip.file("logo.png", e.target.result);
var content = zip.generate({type:"blob"});
// see FileSaver.js
saveAs(content, "test-win.zip");
});
};
reader.readAsArrayBuffer(file);
return false;
});
// Trigger Load Image
$(".trigload").click(function() {
$("input").trigger("click");
});
});
#import url("http://necolas.github.io/normalize.css/3.0.1/normalize.css");
.hide {
display: none;
}
.holder {
text-align: center;
}
.fr {
float: right;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="http://stuk.github.io/jszip/dist/jszip.min.js"></script>
<script type="text/javascript" src="http://stuk.github.io/jszip-utils/dist/jszip-utils.js"></script>
<script type="text/javascript" src="http://stuk.github.io/jszip/vendor/FileSaver.js"></script>
<input type="file" class="hide load">
<a class="trigload" href="javascript:void(0)">Load Image</a>
<a class="download fr" href="javascript:void(0)">Download</a>
<div class="holder"></div>
Weave - https://mikethedj4.github.io/kodeWeave/editor/#4c11c6ef34c5430c0a53be9fd2432092
It's been a year since I've posted this and I just wanted to share another way to do this.
I don't like the idea of using 2 Filereaders so instead I save each image by grabbing it's source and adding it to the zip file.
Here's how it's done!
zip.file("logo.png", $(".imgorigholder > img").attr("src").split('base64,')[1],{base64: true});
Tested using JSZip v2.4.0 (Which is currently outdated).
function displayPreview(file) {
var reader = new FileReader();
reader.onload = function(e) {
var imgorigholder = $(".imgorigholder");
var imgOrigUrl = e.target.result;
var imgOrig = $("<img>");
imgOrig.attr("src", imgOrigUrl);
imgorigholder.empty();
imgorigholder.append(imgOrig);
};
reader.readAsDataURL(file);
exportIt.style.display = "block";
}
// Show zip loader when image has been loaded
loader.onchange = function(evt) {
var file = evt.target.files[0];
displayPreview(file);
};
exportIt.onclick = function() {
var zip = new JSZip();
// Main Icon
zip.file("logo.png", $(".imgorigholder > img").attr("src").split('base64,')[1],{base64: true});
// Files for exported app
zip.file("hello.txt", "Hello sexy mommas");
// Export Chrome Application
var content = zip.generate({type:"blob"});
saveAs(content, "test.zip");
};
button {
display: none;
float: right;
}
.imgorigholder {
text-align: center;
}
<input type="file" id="loader" accept="image/*" />
<button id="exportIt">Save as zip file</button>
<div class="imgorigholder hide"></div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="http://stuk.github.io/jszip/dist/jszip.min.js"></script>
<script src="http://stuk.github.io/jszip-utils/dist/jszip-utils.js"></script>
<script src="http://stuk.github.io/jszip/vendor/FileSaver.js"></script>

Categories

Resources