convert to base64 and send image using ajax in Javascript - javascript

I need to send selected image to the server, here is already I have tried
here is HTML part
<div class="row">
<input type="file" name="filUpload" id="filUpload" onchange="showimagepreview(this)">
<br />
<img id="imgprvw" alt="uploaded image preview" class="img-thumbnail" />
</div>
I need to get encoded image into javascript variable,But I have no idea

for uploading image on to server you need to send image data via AJAX to server side.
for reference you can see this link :
http://www.sanwebe.com/2012/05/ajax-image-upload-and-resize-with-jquery-and-php
http://phppot.com/php/php-ajax-image-upload/

you can try using jquery's base64 plugin. Jquery.Base64 plugin
and do it like this:
function showimagepreview(c) {
var file = c;
if(file.files.length)
{
var reader = new FileReader();
reader.onload = function(e)
{
var b = $.base64.encode(e.target.result);
$("#imgprvw").attr("src", "data:image/png;base64," + b);
};
reader.readAsBinaryString(file.files[0]);
}
}

Related

How do I show an uploaded image in Jquery? [duplicate]

This question already has answers here:
Preview an image before it is uploaded
(29 answers)
Closed 3 years ago.
<html>
<head><script src = "/jquery.js"></script></head>
Test Image Upload
<input type = "file" id = "chooseimage" name = "chooseimage" accept = ".jpg, .jpeg, .png" multiple><br>
<input type = "button" id = "submitimages" value = "Send Image">
<br>
<div id = "test"></div>
<script>
$("#submitimages").click(function(){
var imageinput = $("#chooseimage")[0].files[0];
var reader = new FileReader();
var a = reader.readAsDataURL(imageinput);
reader.onload = function(e)(){}; // what do i do with this?
$("#test").html(a);
});
</script>
</html>
For the Jquery, let me quickly run down my thought process.
1) I get the input id "chooseimage" and grab the files using .files command. I assume .files[0] means to select the first file from the HTML element (but it only selects it, not actually reading it)?
2) create a new FileReader(). I'm not quite sure what this does, I think it allows me to... read the file?
3) But to first read the file using FileReader, we need to convert the file to a base64 encoded string, so we use readAsDataURL to convert.
4) And then I do somrthing with reader.onload(), but I am not sure what this does. I was reading other tutorials on this and they all had it but no explanation what it does. I read the Mozilla Documentation but didn.t quite understand it. I've done nothing with it so far.
5) I want to show the base64 string in the div element with id "test". I think the browser will automatically interpret the string into an image. Either way, it's not showing anything.
Can someone walk me through what I do or do not understand correctly and what I'm doing wrong?
Check this out, and let me know how it goes. :)
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('#imageShow').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgPreview").change(function() {
readURL(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form runat="server">
<input type='file' id="imgPreview" />
<img id="imageShow" src="#" alt="your image" />
</form>

Angular upload image and display to user

Id like to implement a UI where the user selects an image and that image is instantly displayed back to them for review. The user would have to click "submit" to upload/save the image to their profile.
I am having issues with the "instantly display back to the user part".
I am using angular FormData with the following markup & controller:
MARKUP
<input id="chooseFile" type="file" file-model="picFile" />
<img src="{{uploadedImage}}" /> <!-- this populates with filename but what is the path?? -->
CONTROLLER
angular.element('#chooseFile').change(function(){
var file = $scope.picFile; // this comes up "undefined" since file is still uploading when this is fired
$scope.uploadedImage = file.name;
});
I have 2 primary issues with the above code (described in comments):
1) In the controller, file comes up undefined obviously because even the smallest file takes >0s to upload while the callback is fired pretty much instantaneously. I got it work using $timeout but thats a bit of a lame hack. How can I have the callback wait until the file is uploaded??
2) The idea is to upload the file and display it in the img tag using Angular's data-binding. This works in that src is populated with the filename, but what is the path of the img. Some temporary location in cache or something?? Obviously I havent set a path to move the file yet.
Any help appreciated!
I also needed this feature, some how I manage to display image instantly.
angular.module('HelloWorldApp', [])
.controller('HelloWorldController', function($scope) {
$scope.uploadavtar = function(files) {
//var fd = new FormData();
//Take the first selected file
//fd.append("file", files[0]);
var imagefile = document.querySelector('#file');
if (imagefile.files && imagefile.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#temp_image')
.attr('src', e.target.result);
};
reader.readAsDataURL(imagefile.files[0]);
this.imagefile = imagefile.files[0];
}else{
console.log("Image not selected");
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="HelloWorldApp">
<div ng-controller="HelloWorldController">
<input type="file" id="file" onchange="angular.element(this).scope().uploadavtar(this.files)"/>
</div>
<img src="" id="temp_image" width="100">
<div>
</div>
</div>
I was using laravel + Angularjs so another related post to store image is : https://stackoverflow.com/a/34830307/2815635

Retrieve image data from file input without a server

For context, I'm trying to create a "click image" file uploader. Initially there is a default image, which I then click. I trigger a file upload, and the user picks an image file they want. Then I will set the image to replace the default (and do other things with it later). Right now, the front end looks something like this:
<div class="right-preview">
<input type="image" src="img/logo.png" height="240px" width="240px" ng-click="uploadImage('right-image')" id="upload-right-image"/>
<input type="file" id="upload-right" style="visibility: hidden">
</div>
When the image is clicked, it triggers an upload action.
$scope.uploadImage = function(side) {
$image = $('#upload-' + side);
$fileInput = $('#upload-right');
$fileInput.change(function(changeEvent) {
var files = changeEvent.target.files;
for(var i = 0; i < files.length; i++) {
file = files[i];
console.log(file);
}
});
$fileInput.trigger('click');
}
When the change event is fired after the user finishes picking their file, I have the changeEvent and I know they've selected their file. Each of the files has some properties (like name and size) but I'm not seeing anything for accessing the raw data so I can set the src on my other element.
Am I just completely missing how to get the image data, or is there a better way to do this? I have no server (right now) to post this to. Perhaps there is a better way to approach this?
This link may be helpful to you - https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
I took one method from that page and added some additional functionality to hide the file upload button and have the image placeholder trigger its click event.
$('#placeholder').click(function() {
$('#img-upload').trigger('click');
});
function previewFile() {
var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
.hidden {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<img width="250" height="250" id="placeholder" src="http://place-hold.it/250x250&text='click to upload'">
<input class="hidden" type="file" onchange="previewFile()" id="img-upload">

How to get base64 encoded data from html image

I have a registration form where users can choose an avatar. They have 2 possibilities:
Choose a default avatar
Upload their own avatar
In my HTML page I have this.
<img id="preview" src="img/default_1.png">
It displays the chosen avatar.
I use the File Api to let users upload their own image.
That makes the src of the HTML image to something like this.
<img id="preview" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA... />
When they post the registration form. The data will be sent to a REST service.
I can send the base64 encoded data when a user uploaded an avatar himself. But how do I handle the default avatar? It is an url instead of base64 encoded data.
You can try following sample
http://jsfiddle.net/xKJB8/3/
<img id="preview" src="http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG">
<canvas id="myCanvas" />
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("preview");
ctx.drawImage(img, 10, 10);
alert(c.toDataURL());
You can also use the FileReader class :
var reader = new FileReader();
reader.onload = function (e) {
var data = this.result;
}
reader.readAsDataURL( file );

Image size validation

is it possible to validate file image size with jquery class orjavascript ?
Can i do that ? I made some research but did not reach anything
Thank you
If you want to check image file being uploaded on client side, check HTML5 File API. Here are some samples at:
http://www.html5rocks.com/en/tutorials/file/dndfiles/
You can get file size, find it's type and access binary content.
I was using File API to read EXIF headers from image without uploading image to server.
Here is a source code:
https://gist.github.com/980275/85da4a96a3bb23bae97c3eb7ca777acdea7ed791
Try this:
<input type="file" id="loadfile" />
<input type="button" value="find size" onclick="Size()" />
Script:
function Size() {
if ( $.browser.msie ) {
var a = document.getElementById('loadfile').value;
$('#myImage').attr('src',a);
var imgbytes = document.getElementById('myImage').fileSize;
var imgkbytes = Math.round(parseInt(imgbytes)/1024);
alert(imgkbytes+' KB');
}else {
var fileInput = $("#loadfile")[0];
var imgbytes = fileInput.files[0].fileSize; // Size returned in bytes.
var imgkbytes = Math.round(parseInt(imgbytes)/1024);
alert(imgkbytes+' KB');
}
}

Categories