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>
Related
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
}
}
I've been trying to piece together a combination of HTML5 video tag + the FileReader API but I haven't figured out how to get the dimensions of a video that a user is providing from their own computer.
Here is what I am referencing for width/ height:
HTML5 Video Dimensions
<video id="foo" src="foo.mp4"></video>
var vid = document.getElementById("foo");
vid.videoHeight; // returns the intrinsic height of the video
vid.videoWidth; // returns the intrinsic width of the video
But I want to know if it's possible to do this with a file from a user's computer (that they have selected via a normal input html tag).
Thanks!
A bit unclean solution using basic FileReader + Data URL.
<html>
<head>
<style>
div {
margin: 20px;
}
</style>
</head>
<body>
<h1>Get Dimensions</h1>
<div>
<label for="load-file">Load a file:</label>
<input type="file" id="load-file">
</div>
<div>
<button type="button" id="done-button">Get me dimensions</button>
</div>
<script src="//cdn.jsdelivr.net/jquery/2.1.4/jquery.js"></script>
<script>
(function ($) {
$('#done-button').on('click', function () {
var file = $('#load-file')[0].files[0];
var reader = new FileReader();
var fileType = file.type;
console.log("type", fileType);
reader.addEventListener("load", function () {
var dataUrl = reader.result;
var videoId = "videoMain";
var $videoEl = $('<video id="' + videoId + '"></video>');
$("body").append($videoEl);
$videoEl.attr('src', dataUrl);
var videoTagRef = $videoEl[0];
videoTagRef.addEventListener('loadedmetadata', function(e){
console.log(videoTagRef.videoWidth, videoTagRef.videoHeight);
});
}, false);
if (file) {
reader.readAsDataURL(file);
}
});
})(jQuery);
</script>
</body>
</html>
Here is a simple and fast solution to get a video's size before upload.
It doesn't require any dependency.
const url = URL.createObjectURL(file);
const $video = document.createElement("video");
$video.src = url;
$video.addEventListener("loadedmetadata", function () {
console.log("width:", this.videoWidth);
console.log("height:", this.videoHeight);
});
const onSelectVideo = (files) => {
const file = files[0];
const url = URL.createObjectURL(file);
let videoId = "videoMain";
const video = document.createElement("video");
const body = document.getElementsByTagName("body");
video.setAttribute("src", url);
video.setAttribute("videoId", videoId);
body[0]?.append(video);
let videoTagRef = document.querySelector("[videoId='videoMain']");
videoTagRef.addEventListener("loadedmetadata", function (e) {
console.log(videoTagRef.videoWidth, videoTagRef.videoHeight);
});}
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.
I am trying to load a text file into my JavaScript file and then read the lines from that file in order to get information, and I tried the FileReader but it does not seem to be working. Can anyone help?
function analyze(){
var f = new FileReader();
f.onloadend = function(){
console.log("success");
}
f.readAsText("cities.txt");
}
Yeah it is possible with FileReader, I have already done an example of this, here's the code:
<!DOCTYPE html>
<html>
<head>
<title>Read File (via User Input selection)</title>
<script type="text/javascript">
var reader; //GLOBAL File Reader object for demo purpose only
/**
* Check for the various File API support.
*/
function checkFileAPI() {
if (window.File && window.FileReader && window.FileList && window.Blob) {
reader = new FileReader();
return true;
} else {
alert('The File APIs are not fully supported by your browser. Fallback required.');
return false;
}
}
/**
* read text input
*/
function readText(filePath) {
var output = ""; //placeholder for text output
if(filePath.files && filePath.files[0]) {
reader.onload = function (e) {
output = e.target.result;
displayContents(output);
};//end onload()
reader.readAsText(filePath.files[0]);
}//end if html5 filelist support
else if(ActiveXObject && filePath) { //fallback to IE 6-8 support via ActiveX
try {
reader = new ActiveXObject("Scripting.FileSystemObject");
var file = reader.OpenTextFile(filePath, 1); //ActiveX File Object
output = file.ReadAll(); //text contents of file
file.Close(); //close file "input stream"
displayContents(output);
} catch (e) {
if (e.number == -2146827859) {
alert('Unable to access local files due to browser security settings. ' +
'To overcome this, go to Tools->Internet Options->Security->Custom Level. ' +
'Find the setting for "Initialize and script ActiveX controls not marked as safe" and change it to "Enable" or "Prompt"');
}
}
}
else { //this is where you could fallback to Java Applet, Flash or similar
return false;
}
return true;
}
/**
* display content using a basic HTML replacement
*/
function displayContents(txt) {
var el = document.getElementById('main');
el.innerHTML = txt; //display output in DOM
}
</script>
</head>
<body onload="checkFileAPI();">
<div id="container">
<input type="file" onchange='readText(this)' />
<br/>
<hr/>
<h3>Contents of the Text file:</h3>
<div id="main">
...
</div>
</div>
</body>
</html>
It's also possible to do the same thing to support some older versions of IE (I think 6-8) using the ActiveX Object, I had some old code which does that too but its been a while so I'll have to dig it up I've found a solution similar to the one I used courtesy of Jacky Cui's blog and edited this answer (also cleaned up code a bit). Hope it helps.
Lastly, I just read some other answers that beat me to the draw, but as they suggest, you might be looking for code that lets you load a text file from the server (or device) where the JavaScript file is sitting. If that's the case then you want AJAX code to load the document dynamically which would be something as follows:
<!DOCTYPE html>
<html>
<head><meta charset="utf-8" />
<title>Read File (via AJAX)</title>
<script type="text/javascript">
var reader = new XMLHttpRequest() || new ActiveXObject('MSXML2.XMLHTTP');
function loadFile() {
reader.open('get', 'test.txt', true);
reader.onreadystatechange = displayContents;
reader.send(null);
}
function displayContents() {
if(reader.readyState==4) {
var el = document.getElementById('main');
el.innerHTML = reader.responseText;
}
}
</script>
</head>
<body>
<div id="container">
<input type="button" value="test.txt" onclick="loadFile()" />
<div id="main">
</div>
</div>
</body>
</html>
This can be done quite easily using javascript XMLHttpRequest() class (AJAX):
function FileHelper()
{
FileHelper.readStringFromFileAtPath = function(pathOfFileToReadFrom)
{
var request = new XMLHttpRequest();
request.open("GET", pathOfFileToReadFrom, false);
request.send(null);
var returnValue = request.responseText;
return returnValue;
}
}
...
var text = FileHelper.readStringFromFileAtPath ( "mytext.txt" );
Javascript doesn't have access to the user's filesystem for security reasons. FileReader is only for files manually selected by the user.
(fiddle:
https://jsfiddle.net/ya3ya6/7hfkdnrg/2/ )
Usage
Html:
<textarea id='tbMain' ></textarea>
<a id='btnOpen' href='#' >Open</a>
Js:
document.getElementById('btnOpen').onclick = function(){
openFile(function(txt){
document.getElementById('tbMain').value = txt;
});
}
Js Helper functions
function openFile(callBack){
var element = document.createElement('input');
element.setAttribute('type', "file");
element.setAttribute('id', "btnOpenFile");
element.onchange = function(){
readText(this,callBack);
document.body.removeChild(this);
}
element.style.display = 'none';
document.body.appendChild(element);
element.click();
}
function readText(filePath,callBack) {
var reader;
if (window.File && window.FileReader && window.FileList && window.Blob) {
reader = new FileReader();
} else {
alert('The File APIs are not fully supported by your browser. Fallback required.');
return false;
}
var output = ""; //placeholder for text output
if(filePath.files && filePath.files[0]) {
reader.onload = function (e) {
output = e.target.result;
callBack(output);
};//end onload()
reader.readAsText(filePath.files[0]);
}//end if html5 filelist support
else { //this is where you could fallback to Java Applet, Flash or similar
return false;
}
return true;
}
my example
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
</head>
<body>
<script>
function PreviewText() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadText").files[0]);
oFReader.onload = function(oFREvent) {
document.getElementById("uploadTextValue").value = oFREvent.target.result;
document.getElementById("obj").data = oFREvent.target.result;
};
};
jQuery(document).ready(function() {
$('#viewSource').click(function() {
var text = $('#uploadTextValue').val();
alert(text);
//here ajax
});
});
</script>
<object width="100%" height="400" data="" id="obj"></object>
<div>
<input type="hidden" id="uploadTextValue" name="uploadTextValue" value="" />
<input id="uploadText" style="width:120px" type="file" size="10" onchange="PreviewText();" />
</div>
Source file
</body>
</html>
This is an old question but I think in 2022 there are ES6 ways to handle this:
const $node = document.getElementById('output')
const $file = document.getElementById('file')
const processTextByLine = text => {
const arr = text.split(/\r?\n/gm)
arr.map(line => console.log(line))
}
const openFile = event => {
const input = event.target
if (!input) throw new Error('null input')
const [first] = input.files
const reader = new FileReader()
reader.onload = () => {
const text = reader.result
$node.innerText = text
processTextByLine(text)
}
reader.readAsText(first)
}
$file.onchange = openFile
<input id='file' type='file' accept='text/plain'><br>
<div id='output'>
...
</div>
If your file is encoded using UTF-8 then we can make an async call using Blob.text()
const $node = document.getElementById('output')
const $file = document.getElementById('file')
const processTextByLine = text => {
const arr = text.split(/\r?\n/gm)
arr.map(line => console.log(line))
}
const openFile = async event => {
const input = event.target
if (!input) throw new Error('null input')
const [file] = input.files
const text = await file.text()
$node.innerText = text
processTextByLine(text)
}
$file.onchange = openFile
<input id='file' type='file' accept='text/plain'><br>
<div id='output'>
...
</div>
Note:
processTextByLine() function is not needed, it just shows a case if we need to process the file line by line.
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);
}
}
});
});