Display selected image from input file

假如想象 提交于 2021-01-29 09:43:08

问题


my question is how to display the selected file image from the input file in img tag, I have described the code below.

<img src="" width="200" height="100">
<input type="file" name="logo" id="upload-logo" />

$('#upload-logo').on('change', function(){
    let logo = $(this).val();
    $('img').attr('src', logo);
});

but the result I got after changing the src attribute is: Not allowed to load local resource: file: /// C: /fakepath/Capture.PNG, and photos are not displayed

I do not want to use ajax


回答1:


You must use the file reader to validate and allow preview of the uploaded image. the browser disallows the access to local system files for good reason and the file inputs place files in a temporary folder system that the browser is allowed to access.

Here is an example of how to use the File Reader Source

    const reader = new FileReader();

    reader.onload = function(e) {
        // do something with the result
        var file = reader.result || e.target.result;
    }
    reader.readAsDataURL(input.files[0]);



来源:https://stackoverflow.com/questions/57960416/display-selected-image-from-input-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!