开发者

html how to refer to the file in input tag

suppose I have a simple form with a <input type="f开发者_如何学Pythonile"> tag, what i want to do is, once the user select a file, I'd like to display that file(it is an img) on the same page for viewing. better user experience.

tried to set the value based on onChange event, then realized this doesn't work.

any thoughts?


You can't access the client's filesystem from the browser sandbox. It goes against the browser's security model. You'll just have to wait for the user to upload the file before you can display it.


The only way to do this would be to catch onChange event and upload the file using Ajax (asynchronously).

Hint: Submit form on onChange event and send the post data to server-side script.

This technology is used by many websites, though it will be slow if connection of client is slow and the file is big. Good Luck!


You do not need to upload the image before you can display it. Here's a JQuery snippet that will to the trick:

$('input:file').change(function(){
    var file = this.files[0];  
    var reader = new FileReader();  
    reader.onload = (function(event) { 
    $('#previewImage').attr('src',event.target.result); 
    });  
    reader.readAsDataURL(file);   
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜