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

前端 未结 3 691
清歌不尽
清歌不尽 2020-12-16 04:31

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 mach

相关标签:
3条回答
  • 2020-12-16 05:17

    You can use createObjectURL method of the window.URL object, this doesn't have much browser support though

    http://jsfiddle.net/LvAqp/ only works in chrome and firefox

    0 讨论(0)
  • 2020-12-16 05:19

    Using the new File APIs, it is possible to access content from the local disk.

    You put a traditional <input type="file"> upload field on your page, and handle the onchange event.

    MDN has a good writeup with all of the details.

    Your event handler gets a FileList containing Files. From there, you can call FileReader.readAsDataURL(File) to fetch the content of the image and then pass that data URL to an <img> or a <canvas> to do rotation.

    0 讨论(0)
  • 2020-12-16 05:25

    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/

    0 讨论(0)
提交回复
热议问题