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

前端 未结 3 695
清歌不尽
清歌不尽 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条回答
  •  旧时难觅i
    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 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/

提交回复
热议问题