Upload image using javascript - javascript

I'm trying to get image as Object of javascript on the client side to send it using jQuery
<html>
<body>
<script language="JavaScript">
function checkSize()
{
im = new Image();
im.src = document.Upload.submitfile.value;
if(!im.src)
im.src = document.getElementById('submitfile').value;
alert(im.src);
alert(im.width);
alert(im.height);
alert(im.fileSize);
}
</script>
<form name="Upload" action="#" enctype="multipart/form-data" method="post">
<p>Filename: <input type="file" name="submitfile" id="submitfile" />
<input type="button" value="Send" onClick="checkSize();" />
</form>
</body>
</html>
But in this code only alert(im.src) is displaying src of file but alert(im.width),alert(im.height),alert(im.filesize) are not working properly and alerting 0, 0, undefined respectively. Kindly tell me how I can access image object using javascript?

The reason that im.fileSize is only working in IE is because ".fileSize" is only an IE property. Since you have code that works in IE, I would do a check for the browser and render your current code for IE and try something like this for other browsers.
var imgFile = document.getElementById('submitfile');
if (imgFile.files && imgFile.files[0]) {
var width;
var height;
var fileSize;
var reader = new FileReader();
reader.onload = function(event) {
var dataUri = event.target.result,
img = document.createElement("img");
img.src = dataUri;
width = img.width;
height = img.height;
fileSize = imgFile.files[0].size;
alert(width);
alert(height);
alert(fileSize);
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsDataURL(imgFile.files[0]);
}
I haven't tested this code but it should work as long as I don't have some typo. For a better understanding of what I am doing here check out this link.

This is what I use and it works great for me. I save the image as a blob in mysql. When clicked, the file upload dialog appears, that is why i set the file input visibility to hidden and set its type to upload image files. Once the image is selected, it replaces the existing one, then I use the jquery post method to update the image in the database.
<div>
<div><img id="logo" class="img-polaroid" alt="Logo" src="' . $row['logo'] . '" title="Click to change the logo" width="128">
<input style="visibility:hidden;" id="logoupload" type="file" accept="image/* ">
</div>
$('img#logo').click(function(){
$('#logoupload').trigger('click');
$('#logoupload').change(function(e){
var reader = new FileReader(),
files = e.dataTransfer ? e.dataTransfer.files : e.target.files,
i = 0;
reader.onload = onFileLoad;
while (files[i]) reader.readAsDataURL(files[i++]);
});
function onFileLoad(e) {
var data = e.target.result;
$('img#logo').attr("src",data);
//Upload the image to the database
//Save data on keydown
$.post('test.php',{data:$('img#logo').attr("src")},function(){
});
}
});

$('#imagess').change(function(){
var total_images=$('#total_images').val();
var candidateimage=document.getElementById('imagess').value;
formdata = false;
var demo=document.getElementById("imagess").files;
if (window.FormData) {
formdata = new FormData();
}
var i = 0, len = demo.length, img, reader, file;
for ( ; i < len; i++ ) {
file = demo[i];
if (file.type.match(/image.*/)) {
if (formdata) {
formdata.append("images", file);
}
}
}
$('#preview').html('Uploading...');
var url=SITEURL+"users/image_upload/"+total_images;
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
$('#preview').html('');
if (res == "maxlimit") {
alert("You can't upload more than 4 images");
}
else if (res == "error") {
alert("Image can't upload please try again.")
}
else {
$('#user_images').append(res);
}
}
});
});

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]);

AngularJS: Is there any way to get size of file?

I'm implementing a check in which I dont want to upload the image which has size greater than 4MB. I'm using file reader and new image(). I've the image size and width. But how can I get the filesize.
function previewImage(element) {
var reader = new FileReader();
reader.onload = function (event) {
seAddArtist.imageSource = event.target.result;
$scope.$apply();
};
// when the file is read it triggers the onload event above.
reader.readAsDataURL(element.files[0]);
}
var img = new Image();
img.onload = function () {
alert(this.width + 'x' + this.height);
}
I am implementing these two combine but how can i check the size of image?
FileReader (FileReader API) itself does not provide the size of an file. You need to use file (file API) instead:
function previewImage(element) {
var reader = new FileReader();
reader.onload = function(event) {
seAddArtist.imageSource = event.target.result;
$scope.$apply();
};
// when the file is read it triggers the onload event above.
reader.readAsDataURL(element.files[0]);
//log / access file size in bytes
console.log(element.files[0].size + ' Bytes');
//log / access file size in Mb
console.log(element.files[0].size/1024/1024 + ' MB');
if (element.files[0].size/1024/1024 > 4) {
console.log('file is bigger than 4MB);
}
}
That might be what you want:
var size = files[0].size;
You can check the file size before submitting:
<!doctype HTML>
<html>
<head>
<script>
function checkFileSize() {
var size = document.getElementById("fileSelector").files[0].size;
alert("file size: " + size);
}
</script>
</head>
<body>
<input id="fileSelector" type="file" onchange="checkFileSize()"/>
<input type="submit" />
</body>
</html>
This is working code to get file size. you will get file size in KB.
<input id="file" type="file">
<img id="filerendered" src="">
and in script tag
document.getElementById('file').onchange = function (event) {
var targetn = event.target || window.event.srcElement,
files = targetn.files;
// FileReader here
if (FileReader && files && files.length) {
var thisReader = new FileReader();
alert("your file size "+ (files[0].size)/1024 + "kb")
thisReader.onload = function () {
document.getElementById("filerendered").src = thisReader.result;
}
thisReader.readAsDataURL(files[0]);
}
// for Not supported case
else {
// not supported
}
}

div used for image display causing difficulties while uploading file;

Here i have a image upload mechanism. It's purpose is to accept an image and display it in a div with id=imageholder . My problem is if i have this image holder div inside my form , it gives upload error (4) . So i get an empty $_FILES array. But if i omit it i get a populated $_FILES array .But i need that div inside the form for design purpose. How i can escape this situation .
with imagehoder div inside form:
without imageholder div :
code may seem long . But none of it is related to the question. It is generally for validating the mime type
full code :
<?php print_r($_FILES);?>
<html>
<body>
<form method='post' enctype='multipart/form-data' action="<?php echo $_SERVER['PHP_SELF'] ?>">
<div id='photouploder'>
<div id='imagehoder'></div> // creating problem
<div class="inputWrapper">upload image
<input class="fileInput" id='up' type="file" name="image"/>
</div>
</div>
<input type='submit' value='submit'>
</form>
<script>
var imageholder=document.getElementById('imageholder');
function getBLOBFileHeader(url, blob, callback,callbackTwo) {
var fileReader = new FileReader();
fileReader.onloadend = function(e) {
var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
var header = "";
for (var i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
var imgtype= callback(url, header);// headerCallback
callbackTwo(imgtype,blob)
};
fileReader.readAsArrayBuffer(blob);
}
function headerCallback(url, headerString) {
var info=getHeaderInfo(url, headerString);
return info;
}
function getTheJobDone(mimetype,blob){
var mimearray=['image/png','image/jpeg','image/gif'];
console.log('mimetype is :'+mimetype);
if(mimearray.indexOf(mimetype) !=-1){
printImage(blob);
}else{
document.getElementById('up').value='';
while (imageholder.firstChild) {
imageholder.removeChild(imageholder.firstChild);
}
console.log('you can not upload this file type');
}
}
function remoteCallback(url, blob) {
getBLOBFileHeader(url, blob, headerCallback,getTheJobDone);
}
function printImage(blob) {
// Add this image to the document body for proof of GET success
var fr = new FileReader();
fr.onloadend = function(e) {
var img=document.createElement('img');
img.setAttribute('src',e.target.result);
img.setAttribute('style','width:100%;height:100%;');
imageholder.appendChild(img);
};
fr.readAsDataURL(blob);
}
function mimeType(headerString) {
switch (headerString) {
case "89504e47":
type = "image/png";
break;
case "47494638":
type = "image/gif";
break;
case "ffd8ffe0":
case "ffd8ffe1":
case "ffd8ffe2":
type = "image/jpeg";
break;
default:
type = "unknown";
break;
}
return type;
}
function getHeaderInfo(url, headerString) {
return( mimeType(headerString));
}
// Check for FileReader support
function fileread(event){
if (window.FileReader && window.Blob) {
/* Handle local files */
var mimetype;
var mimearray=['image/png','image/jpeg','image/gif'];
var file = event.target.files[0];
if(mimearray.indexOf(file.type)===-1 || file.size >= 2 * 1024 * 1024){
while (imageholder.firstChild) {
imageholder.removeChild(imageholder.firstChild);
}
document.getElementById('up').value='';
console.log("you can't upload this file type");
file=null;
return false;
}else{
while (imageholder.firstChild) {
imageholder.removeChild(imageholder.firstChild);
}
document.getElementById('up').value='';
remoteCallback(file.name, file);
}
}else {
// File and Blob are not supported
console.log('file and blob is not supported');
} /* Drakes, 2015 */
}
document.getElementById('up').addEventListener('change',fileread,false);
</script>
</body>
</html>
First of all: HTML attribute values should always be encapsulated in double quotes.
Second, this is a correct example of reading files using html5 API like you tried:
(Also check the documentation for it: https://developer.mozilla.org/en-US/docs/Web/API/FileReader)
window.onload = function() {
var fileInput = document.getElementById('up');
var fileDisplayArea = document.getElementById('imagehoder');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var imageType = /image.*/;
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerHTML = "";
var img = new Image();
img.src = reader.result;
fileDisplayArea.appendChild(img);
}
reader.readAsDataURL(file);
} else {
fileDisplayArea.innerHTML = "File not supported!"
}
});
}
<body>
<form method="post" enctype='multipart/form-data' action="<?php echo $_SERVER['PHP_SELF'] ?>">
<div id="photouploder">
<div id="imagehoder"></div>
<div class="inputWrapper">upload image
<input class="fileInput" id="up" type="file" name="image" />
</div>
</div>
<input type="submit" value="submit">
</form>
</body>
I'm not sure about the 'design purpose' in your question. If the 'design purpose' means UI design (CSS related), then probably this reason doesn't stand since they are totally irrelevant.
Also, the file upload technology is very mature now. There are bunches of open source implements in all languages and are well-tested and easy-to-use I highly recommend you to take a look at them before implementing it yourself.

How to get base64 from input file in IE without using FileReader or HTML5

I hope I can have help from you. I need to get a file from an HTML input file element.
This is the HTML:
<input type="file" name="allegatoImg" id="allegatoImg" onchange="javascript:readURL(this)"/>
And this is JavaScript:
function readURL(input) {
var mimeType;
if (window.FileReader) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
var dataURL = e.target.result;
mimeType = dataURL.split(",")[0].split(":")[1].split(";")[0];
if (mimeType == 'image/jpeg') {
jQuery('#imgallegato').attr('src', e.target.result);
//jQuery('#fotoTemp').attr('src', e.target.result);
provaInvioImgSrcToServer();
} else {
alert('Errore nella lettura del file. Controllare che sia stato caricato un file con estensione jpeg.');
return;
}
};
reader.readAsDataURL(input.files[0]);
}
} else {
f = document.dettRichAbbForm;
document.getElementById("imgallegato").src = "file:///" + input.value;
var estensione = ctrlExtensionFileIE(input.value);
alert('path file = ' + jQuery("#imgallegato").attr('src') );
if (estensione=='jpg' || estensione=='jpeg') {
provaInvioImgSrcToServer();
} else {
alert('Error in reading file');
return;
}
}
}
function provaInvioImgSrcToServer() {
var urlToCall = provaInvioImgSrcToServerUrl;
alert('img path = ' + jQuery("#imgallegato").attr('src'));
jQuery.ajax({
cache : false,
type : "POST",
timeout : 5000,
url : urlToCall,
data : {imgSource: jQuery("#imgallegato").attr('src')},
success : function(result) {
ritagliaImg();
},
error : function(errorMsg) {
//gestAjaxCallError(errorMsg, divResultBodId, divResultBodId);
alert('Errore nel caricamento dell\'immagine selezionata.');
}
});
}
function ctrlExtensionFileIE(value) {
var splittedVal = value.split(".");
return splittedVal[1];
}
I'm working on Liferay 5.1 with an old version of jQuery so I can't use HTML5 with canvas element, because I should load the image from the input file into a Jcrop element.
My problem is linked to this part of the code:
f = document.dettRichAbbForm;
document.getElementById("imgallegato").src = "file:///" + input.value;
FileReader works fine in Mozilla, Chrome and IE10+, but with IE9- I should use the code above.
The problem is that input.value returns the path of the selected file and I need to get the base64 in order to send it to the server. I can't do the submit of my form, because this approach needs to re-load my jsp and I have others fields.
Is there someone that could help me to get the byte array from selected file on IE without using canvas element, HTML5 and FileReader library?

replace XMLHttpRequest in javascript

I used to read my local files using XMLHttpRequest.
function getData(fileName)
{
var filePath = fileName;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", filePath, false);
xmlhttp.send(null);
var fileContent = xmlhttp.responseText;
var tempArr = csv2Arr(fileContent);
var returnLabelArr = tempArr[0].toString().split(',');
tempArr.shift();
var returnDataArr = tempArr;
return { 'dataArr' : returnDataArr, 'labelArr' : returnLabelArr };
}
fileName starts with "C://..." and my program works on browser with address "file:///...".
But, without "--allow-file-access-from-files" tag, my code doesn't work on Chrome. And also it doesn't work on IE and Firefox without changing some security options.
So, I tried to jquery API like this,
function getData(fileName)
{
var filePath = fileName;
var fileContent;
$.ajax({
type: "GET",
url: filePath
})
.done(function(data) {
alert(data);
fileContent = data;
});
var tempArr = csv2Arr(fileContent);
var returnLabelArr = tempArr[0].toString().split(',');
tempArr.shift();
var returnDataArr = tempArr;
return { 'dataArr' : returnDataArr, 'labelArr' : returnLabelArr };
}
The Problem also occurs. I think Same-origin policy prevents it.
Can anyone give me some suggestions for me to access local files without changing security options? Should I use some plug-ins to solve this?
Please let me know.
Thank you.
If you can use <input type="file"> to select files, then the solution is:
HTML:
<form action="">
<input type="file" id="file-input" multiple="multiple" accept="image/jpeg" />
</form>
JS:
var fileInput = document.querySelector('#file-input');
fileInput.addEventListener('change', function(event) {
var files = fileInput.files;
if (files.lenght == 0) {
return;
}
for(var i = 0; i < files.length; i++) {
readFile(files[i]);
}
fileInput.value = "";
}, false);
var readFile= function(file) {
var reader = new FileReader();
reader.onload = function(e) {
var dataUrl = e.target.result;
// now, load the data into some element
// if this is image, you can do this:
var image = new Image();
image.src = dataUrl;
document.body.appendChild(image);
};
reader.readAsDataURL(file);
};
Also, discover the FileReader API to find out, how you can use it otherwise, as it has more methods to read data.

Categories

Resources