I need to show upload image before upload using jquery but in chrome path shown fake path like this:
C:\fakepath\myImage.jpg
and in firefox it's shown only file name:
myImage.jpg
so how can me preview my image file before uploading
<input type="file">
<img src="" class="preview" />
if that is impossible.. what about HTML5?
I don't know of a jQuery function (sorry), but it is possible with HTML5, and most browsers support this HTML5 function. I found a piece of code in HTML5rocks (1):
<style>
.thumb {
height: 75px;
border: 1px solid #000;
margin: 10px 5px 0 0;
}
</style>
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
Good luck :)
(1) HTML5rocks - Reading Files: http://www.html5rocks.com/en/tutorials/file/dndfiles/
You can't. You need to upload image using ajax, for example, return image url and finally display it.
Related
I created a function to upload images, however I am having trouble viewing these images ...
My problem: When I click the button to select an image, I select an image and would like it to fill the entire box.
Image 1 illustrates the problem (image fills the entire border)
Problem 2: When I select more than one image, they are all in line in the giant box ... the goal was to have 1 image filling the big box and the remaining ones filling the small boxes.
Image 2 illustrates the problem.
In this image below I illustrate better what I intend.
Please someone help me !
MY CODEPEN
Javascript
var drop = $("input");
drop.on('dragenter', function (e) {
$(".drop").css({
"border": "4px dashed #09f",
"background": "rgba(0, 153, 255, .05)"
});
$(".cont").css({
"color": "#09f"
});
}).on('dragleave dragend mouseout drop', function (e) {
$(".drop").css({
"border": "3px dashed #DADFE3",
"background": "transparent"
});
$(".cont").css({
"color": "#8E99A5"
});
});
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function (theFile) {
return function (e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumbs" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
$('#files').change(handleFileSelect);
Please review this codepen approach.
You need to add this things:
<div class="Upcard">
<div class="card-block" id="2">
</div>
</div>
CSS:
/* Images Module */
img {
/* bootstrap was overalaping this feature */
width: 100% !important;
}
.card-block> img {
height: 100% !important;
}
JS modify:
var enter = false;
reader.onload = (function (theFile) {
return function (e) {
// Render thumbnail.
if (!enter) {
var list = document.getElementById('list');
list.innerHTML = ['<img class="thumbs" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'].join('');
enter = true;
} else {
// you need to loop here, Im sorry I do not remember the looping thing, but this is the approach...
var card = document.getElementById('2');
card.innerHTML = ['<img class="thumbs" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'].join('');
}
};
})(f);
https://codepen.io/MarchWhitetower/pen/yLLMerV
below is my snippet, and what I'm trying to do is render the selected image (from the input file) to the specified image container ("#test_image") but unfortunately, it looks like missed up and sadly not working. Any ideas, help?
var prev_image;
$(document).ready(function(){
$("input[type='file']").change(function(){
//get the val of the previous image for the reset use later
prev_image = $("#test_image").attr("src");
//render the selected image on the image box (test_image)
$("#test_image").attr("src", $(this).val());
})
});
#test_image{
width: 100px;
height: 100px;
-webkit-border-radius: 50%;-moz-border-radius: 50%;border-radius: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="test_image" src="data:image/jpg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxITEhUSExAUFBIVFBYZ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fuLt29hM2y2TqvGcsdy+FdSMMINvBJtvYs2dWx3PtqPD+FPPtewndWsW2tCyWSVR4JZbZPor9eBQ2WzRprCPa9r+9xkhFJYJJJaJaHo44AAAAAAAAAAAAAAAAAAAAAB5qwjJYSipLjs6nqj0AObWuWD6E3HhL3o96z8zSq3PWWkVJb4yT8NfA74AlqlmnHWEl1xZiZX857xznvfeOBIIyQs03pCT6osq+c97HOe8cCepXRWesVFb5SS8NfA3aNyxXSm5cI+6u95nTAHijSjFYRiorh9XtPYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB/9k="/>
<input type="file" />
HTML5 comes with File API spec, which allows you to create applications that let the user interact with files locally; That means you can load files and render them in the browser without actually having to upload the files. Part of the File API is the FileReader interface which lets web applications asynchronously read the contents of files .
var prev_image;
$(document).ready(function(){
$("input[type='file']").change(function(){
// handle input changes
prev_image = $("#test_image").attr("src");
// grab the first image in the FileList object and pass it to the function
renderImage(this.files[0])
});
});
// render the image in our view
function renderImage(file) {
// generate a new FileReader object
var reader = new FileReader();
// inject an image with the src url
reader.onload = function(event) {
the_url = event.target.result
$('#test_image').attr('src',the_url);
}
// when the file is read it triggers the onload event above.
reader.readAsDataURL(file);
}
#test_image{
width: 100px;
height: 100px;
-webkit-border-radius: 50%;-moz-border-radius: 50%;border-radius: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="test_image" src="data:image/jpg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxITEhUSExAUFBIVFBYZGBMTEQ8QEBYXFBcXGBUUGBQYHSghGBolHBUUITEiJykrLi4uGB8zODMsNygtLisBCgoKDg0OGxAQGzQkHyQsLCwsLCwsLDUsLCwsLCwsLCwsLCwrLCwsLCwsLDUsLCwrLCssLDQsLCwsLCwsLCwsK//AABEIAOEA4QMBIgACEQEDEQ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b4yT8NfA74AlqlmnHWEl1xZiZX857xznvfeOBIIyQs03pCT6osq+c97HOe8cCepXRWesVFb5SS8NfA3aNyxXSm5cI+6u95nTAHijSjFYRiorh9XtPYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB/9k="/>
<input type="file" />
One of Sort trick
<input type="file" onchange="$('#test_image')[0].src = window.URL.createObjectURL(this.files[0])" />
here the fiddle
http://jsfiddle.net/LvsYc/7050/
You need to read the file using file api to set the src of the image
var prev_image;
$(document).ready(function() {
$("input[type='file']").change(function() {
//get the val of the previous image for the reset use later
prev_image = $("#test_image").prop("src");
var reader = new FileReader();
reader.onloadend = function() {
$("#test_image").prop("src", reader.result);
}
if (this.files && this.files[0]) {
reader.readAsDataURL(this.files[0]);
} else {
$("#test_image").prop("src", "");
}
})
});
#test_image {
width: 100px;
height: 100px;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
border-radius: 50%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="test_image" src="data:image/jpg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxITEhUSExAUFBIVFBYZGBMTEQ8QEBYXFBcXGBUUGBQYHSghGBolHBUUITEiJykrLi4uGB8zODMsNygtLisBCgoKDg0OGxAQGzQkHyQsLCwsLCwsLDUsLCwsLCwsLCwsLCwrLCwsLCwsLDUsLCwrLCssLDQsLCwsLCwsLCwsK//AABEIAOEA4QMBIgACEQEDEQH/xAAbAAEBAAMBAQEAAAAAAAAAAAAABgMEBQIBB//EAD0QAAIBAQUDCQYDCAMBAAAAAAABAgMEBREhMUFRYQYSMnGBkaGx0RMiQlLB8DNy4SNTYnOCkqLCJEPxsv/EABkBAQEBAQEBAAAAAAAAAAAAAAADAgEEBf/EAB0RAQEBAAMBAQEBAAAAAAAAAAABAhEhMRIDEzL/2gAMAwEA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>
<input type="file" />
Use Html2Canvas for taking screen shot .Its very easy .. just include the html2canvas js files.. you will get from Here
and some simple codes . Refer this -> Click Here
It will work for you .
In your case you can use a temp image path.
Here is the fiddle: http://jsfiddle.net/swaprks/91Lphm16/
CSS:
#test_image{
width: 100px;
height: 100px;
-webkit-border-radius: 50%;-moz-border-radius: 50%;border-radius: 50%;
}
JS:
var prev_image;
$(document).ready(function(){
$("input[type='file']").change(function(event){
var tmppath = URL.createObjectURL(event.target.files[0]);
//get the val of the previous image for the reset use later
prev_image = $("#test_image").attr("src");
//render the selected image on the image box (test_image)
$("#test_image").attr("src", tmppath);
})
});
HTML:
<img id="test_image" src="data:image/jpg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxITEhUSExAUFBIVFBYZGBMTEQ8QEBYXFBcXGBUUGBQYHSghGBolHBUUITEiJykrLi4uGB8zODMsNygtLisBCgoKDg0OGxAQGzQkHyQsLCwsLCwsLDUsLCwsLCwsLCwsLCwrLCwsLCwsLDUsLCwrLCssLDQsLCwsLCwsLCwsK//AABEIAOEA4QMBIgACEQEDEQH/xAAbAAEBAAMBAQEAAAAAAAAAAAAABgMEBQIBB//EAD0QAAIBAQUDCQYDCAMBAAAAAAABAgMEBREhMUFRYQYSMnGBkaGx0RMiQlLB8DNy4SNTYnOCkqLCJEPxsv/EABkBAQEBAQEBAAAAAAAAAAAAAAADAgEEBf/EAB0RAQEBAAMBAQEBAAAAAAAAAAABAhEhMRIDEzL/2gAMAwEAAhEDEQA/AP0IAHz3gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADDaLVCHSlhw1fcBmBx698/JHtl6I0qtvqS1m11ZeRzkUrMbrR+aP8AciVk8dXj15nwcuKtVo/PH+5HtMkT7F4aZdWQ5FcCZpW+pHSb7c/M3aF8v449scvBjl12QYLPa4T6Ms92j7jOdAAAAAAAAAAAAAAAAAAAAAAPFWrGKxk8EYrba401i829Ftf6E9abTKbxk+pbF1Ab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1b0I6+70daWEcqa0W9/MxfF7yrPmr3aa2bXxfoaFnoSnJRis/BcWR1rnqJa1z1HuxWV1Jc1aat7l6lLCCSSSwSySMdksypx5q7XtbMxlkAAAAAAAAAAAAAAABjtNCNSPNkstj+KL3r0J63WGVN55xekl0X6PgUoaTTTSaeqeaYEvZLXOm+dCTT2rY+tbSmu/lDTnlU9yW/4H27O05dsubbSf9Enn2S29pyKkHF4STTWxrBnZbl2Wx+hxkmsU8VvWaPpA2a2VKfQm48NV3PI61n5TTXTgpcV7rNz9I3NxUA4tLlLResZx7E14M2Fftn/ed8ZL6GvqNfUdIHNd+2f95/jL0MFXlJRWinLsSXizv1D6jsnxvDN5LjkiYtHKab6EFHi3zmcm1W2pU6c2+Gke5ZGb+kZu4prfygpwyh+0lwfuLt29hM2y2TqvGcsdy+FdSMMINvBJtvYs2dWx3PtqPD+FPPtewndWsW2tCyWSVR4JZbZPor9eBQ2WzRprCPa9r+9xkhFJYJJJaJaHo44AAAAAAAAAAAAAAAAAAAAAB5qwjJYSipLjs6nqj0AObWuWD6E3HhL3o96z8zSq3PWWkVJb4yT8NfA74AlqlmnHWEl1xZiZX857xznvfeOBIIyQs03pCT6osq+c97HOe8cCepXRWesVFb5SS8NfA3aNyxXSm5cI+6u95nTAHijSjFYRiorh9XtPYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB/9k="/>
<input type="file" />
Try this. Do some tweeking as per your need
var prev_image;
$(document).ready(function(){
$("input[type='file']").change(function(){
var tmpImageData = new FileReader();
tmpImageData.onload = function (e) {
//get the val of the previous image for the reset use later
prev_image = $("#test_image").attr("src");
//render the selected image on the image box (test_image)
$("#test_image").attr("src", e.target.result);
}
tmpImageData.readAsDataURL(input.files[0]);
})
});
I'm using the following code to upload an image for viewing before passing it on to my server. I want to put constraints on the size of the image using css. The CSS is having no effect on the image as it is rendered by output. Is there a way around this? I tried adding the CSS attribute to its surrounding div but that did not work either.
The HTML:
<input type="file" id="files" name="files[]" file-model="myFile"/>
<output id="list" class="resize-image" alt="Image"></output>
The CSS:
#list{
max-width: 15px;
max-height: 7px;
}
The Javascript:
var handleFileSelect = function (evt) {//already set up for multiple files; not what i want to do.
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
The simples would be to use height and width img tag attributes.
var span = document.createElement('span');
span.innerHTML = ['<img height="7" width="15" class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('list').insertBefore(span, null);
If you really would like to use .css for this task you can use background-size, but then background property must be set with url to the image in css.
You can also simply override the img tag in css like this:
img{
max-width: 100px;
max-height: 100px;
}
Here you can test both approaches : http://www.w3schools.com/cssref/tryit.asp?filename=trycss3_background-size
Can I kindly ask for a good working example of HTML5 File Drag and Drop implementation? The source code should work if drag and drop is performed from external application(Windows Explorer) to browser window. It should work on as many browsers as possible.
I would like to ask for a sample code with good explanation. I do not wish to use third party libraries, as I will need to modify the code according to my needs. The code should be based on HTML5 and JavaScript. I do not wish to use JQuery.
I spent the whole day searching for good source of material, but surprisingly, I did not find anything good. The examples I found worked for Mozilla but did not work for Chrome.
Here is a dead-simple example. It shows a red square. If you drag an image over the red square it appends it to the body. I've confirmed it works in IE11, Chrome 38, and Firefox 32. See the Html5Rocks article for a more detailed explanation.
var dropZone = document.getElementById('dropZone');
// Optional. Show the copy icon when dragging over. Seems to only work for chrome.
dropZone.addEventListener('dragover', function(e) {
e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
});
// Get file data on drop
dropZone.addEventListener('drop', function(e) {
e.stopPropagation();
e.preventDefault();
var files = e.dataTransfer.files; // Array of all files
for (var i=0, file; file=files[i]; i++) {
if (file.type.match(/image.*/)) {
var reader = new FileReader();
reader.onload = function(e2) {
// finished reading file data.
var img = document.createElement('img');
img.src= e2.target.result;
document.body.appendChild(img);
}
reader.readAsDataURL(file); // start reading the file data.
}
}
});
<div id="dropZone" style="width: 100px; height: 100px; background-color: red"></div>
The accepted answer provides an excellent link for this topic; however, per SO rules, pure link answers should be avoided since the links can rot at any time. For this reason, I have taken the time to summarize the content of the link for future readers.
Getting Started
Prior to implementing a method to upload files to your website, you should ensure that the browsers you choose to support will be capable of fully supporting the File API. You can test this quickly with the snippet of Javascript below:
// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
// Great success! All the File APIs are supported.
} else {
alert('The File APIs are not fully supported in this browser.');
}
You can modify the snippet above to meet your needs of course.
Form Input
The most common way to upload a file is to use the standard <input type="file"> element. JavaScript returns the list of selected File objects as a FileList.
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
f.size, ' bytes, last modified: ',
f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
'</li>');
}
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>
Drag and Drop
Making simple modifications to the snippet above allows us to provide drag and drop support.
function handleFileSelect(evt) {
evt.stopPropagation();
evt.preventDefault();
var files = evt.dataTransfer.files; // FileList object.
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
f.size, ' bytes, last modified: ',
f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
'</li>');
}
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
}
function handleDragOver(evt) {
evt.stopPropagation();
evt.preventDefault();
evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
}
// Setup the dnd listeners.
var dropZone = document.getElementById('drop_zone');
dropZone.addEventListener('dragover', handleDragOver, false);
dropZone.addEventListener('drop', handleFileSelect, false);
#drop_zone {
min-height: 10em;
background: #eee;
}
<div id="drop_zone">Drop files here</div>
<output id="list"></output>
Reading Files
Now you've obtained a reference to the File, you can instantiate a FileReader to read its contents into memory. When the load completes the onload event is fired and its result attribute can be used to access the file data. Feel free to look at the references for FileReader to cover the four available options for reading a file.
The example below filters out images from the user's selection, calls reader.readAsDataURL() on the file, and renders a thumbnail by setting the src attribute to a data URL.
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
.thumb {
height: 75px;
border: 1px solid #000;
margin: 10px 5px 0 0;
}
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>
Slicing
In some cases reading the entire file into memory isn't the best option. For example, say you wanted to write an async file uploader. One possible way to speed up the upload would be to read and send the file in separate byte range chunks. The server component would then be responsible for reconstructing the file content in the correct order.
The following example demonstrates reading chunks of a file. Something worth noting is that it uses the onloadend and checks the evt.target.readyState instead of using the onload event.
function readBlob(opt_startByte, opt_stopByte) {
var files = document.getElementById('files').files;
if (!files.length) {
alert('Please select a file!');
return;
}
var file = files[0];
var start = parseInt(opt_startByte) || 0;
var stop = parseInt(opt_stopByte) || file.size - 1;
var reader = new FileReader();
// If we use onloadend, we need to check the readyState.
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
document.getElementById('byte_content').textContent = evt.target.result;
document.getElementById('byte_range').textContent =
['Read bytes: ', start + 1, ' - ', stop + 1,
' of ', file.size, ' byte file'].join('');
}
};
var blob = file.slice(start, stop + 1);
reader.readAsBinaryString(blob);
}
document.querySelector('.readBytesButtons').addEventListener('click', function(evt) {
if (evt.target.tagName.toLowerCase() == 'button') {
var startByte = evt.target.getAttribute('data-startbyte');
var endByte = evt.target.getAttribute('data-endbyte');
readBlob(startByte, endByte);
}
}, false);
#byte_content {
margin: 5px 0;
max-height: 100px;
overflow-y: auto;
overflow-x: hidden;
}
#byte_range { margin-top: 5px; }
<input type="file" id="files" name="file" /> Read bytes:
<span class="readBytesButtons">
<button data-startbyte="0" data-endbyte="4">1-5</button>
<button data-startbyte="5" data-endbyte="14">6-15</button>
<button data-startbyte="6" data-endbyte="7">7-8</button>
<button>entire file</button>
</span>
<div id="byte_range"></div>
<div id="byte_content"></div>
Monitoring Progress
One of the nice things that we get for free when using async event handling is the ability to monitor the progress of the file read; useful for large files, catching errors, and figuring out when a read is complete.
The onloadstart and onprogress events can be used to monitor the progress of a read.
The example below demonstrates displaying a progress bar to monitor the status of a read. To see the progress indicator in action, try a large file or one from a remote drive.
var reader;
var progress = document.querySelector('.percent');
function abortRead() {
reader.abort();
}
function errorHandler(evt) {
switch(evt.target.error.code) {
case evt.target.error.NOT_FOUND_ERR:
alert('File Not Found!');
break;
case evt.target.error.NOT_READABLE_ERR:
alert('File is not readable');
break;
case evt.target.error.ABORT_ERR:
break; // noop
default:
alert('An error occurred reading this file.');
};
}
function updateProgress(evt) {
// evt is an ProgressEvent.
if (evt.lengthComputable) {
var percentLoaded = Math.round((evt.loaded / evt.total) * 100);
// Increase the progress bar length.
if (percentLoaded < 100) {
progress.style.width = percentLoaded + '%';
progress.textContent = percentLoaded + '%';
}
}
}
function handleFileSelect(evt) {
// Reset progress indicator on new file selection.
progress.style.width = '0%';
progress.textContent = '0%';
reader = new FileReader();
reader.onerror = errorHandler;
reader.onprogress = updateProgress;
reader.onabort = function(e) {
alert('File read cancelled');
};
reader.onloadstart = function(e) {
document.getElementById('progress_bar').className = 'loading';
};
reader.onload = function(e) {
// Ensure that the progress bar displays 100% at the end.
progress.style.width = '100%';
progress.textContent = '100%';
setTimeout("document.getElementById('progress_bar').className='';", 2000);
}
// Read in the image file as a binary string.
reader.readAsBinaryString(evt.target.files[0]);
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
#progress_bar {
margin: 10px 0;
padding: 3px;
border: 1px solid #000;
font-size: 14px;
clear: both;
opacity: 0;
-moz-transition: opacity 1s linear;
-o-transition: opacity 1s linear;
-webkit-transition: opacity 1s linear;
}
#progress_bar.loading {
opacity: 1.0;
}
#progress_bar .percent {
background-color: #99ccff;
height: auto;
width: 0;
}
<input type="file" id="files" name="file" />
<button onclick="abortRead();">Cancel read</button>
<div id="progress_bar"><div class="percent">0%</div></div>
Look into ondragover event. You could simply have a inside of a div that is hidden until the ondragover event fires a function that will show the div with the in it, thus letting the user drag and drop the file. Having an onchange declaration on the would let you automatically call a function (such as upload) when a file is added to the input. Make sure that the input allows for multiple files, as you have no control over how many they are going to try and drag into the browser.
This technique works very well, but if you want a binary blob rather than just to put the dragged image in an html img element, you'll need to use the 'fetch' function twice.
The idea is to take an image from a user's machine and allow them to display the image in a webpage. I do not want to send the image back to the server.
An upload button will exist. It should just update the page content dynamically.
Can this be done with HTML5 localstorage or anything?
FileReader is capable of doing this. Here's sample code:
<input type="file" id="files" name="files[]" multiple />
<img id="image" />
<script>
function onLoad(evt) {
/* do sth with evt.target.result - it image in base64 format ("data:image/jpeg;base64,....") */
localStorage.setItem('image', evt.target.result);
document.getElementById('image').src = evt.target.result;
};
function handleFileUpload(evt) {
var files = evt.target.files; // FileList object
for (var i = 0; i < files.length; i++) {
var f = files[i];
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
reader.onload = onLoad;
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileUpload, false);
var image = localStorage.getItem('image');
if (image !== null) {
document.getElementById('image').src = image;
}
</script>
Yeah absolutely, providing you have a cutting edge browser (Chrome or Firefox).
You want to use FileReader and readAsDataURL(). Take a look at the third example in this tutorial:
http://www.html5rocks.com/en/tutorials/file/dndfiles/