Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load images from the local machine to JS object avoiding loading to the server

I want to load an image file from the computer directly to any js object without using any server-side component. For example, I want to select a picture from the local machine and display it on a webpage. Is there a way to avoid file upload to the server?

In fact I want to write a kind of multiple image loader, but before loading to the server I want to rotate some images, create an xml-file with some data like user id, image file names list and to zip all images and this xml and then send it to the server. How can I do that on the client side?

like image 321
hexonxons Avatar asked Jul 22 '12 20:07

hexonxons


1 Answers

There is a way with HTML5, but it requires the user to have dropped the file into a drop target or used a <input type="file"/> box, since otherwise it would be a security issue.

Using the File API you can read files, and specifically you can use the FileReader.readAsDataURL method to set the content as a data: URL for the image tag.

Here's an example:

$('#f').on('change', function(ev) {
    var f = ev.target.files[0];
    var fr = new FileReader();

    fr.onload = function(ev2) {
        console.dir(ev2);
        $('#i').attr('src', ev2.target.result);
    };

    fr.readAsDataURL(f);
});​

http://jsfiddle.net/alnitak/Qszjg/

like image 183
Alnitak Avatar answered Oct 24 '22 19:10

Alnitak