使用javascript获取文件输入? [英] Get file input with javascript?

查看:69
本文介绍了使用javascript获取文件输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在HTML中有这一行:

I have this line in HTML:

<input class="input-file" type="file" id="input-recipe-pic"> 

在用户选择要上传的文件并按下提交"按钮之后,我试图从上面的文件输入标签中获取他们选择的文件.如何使用javascript获取文件,以便以后可以通过AJAX发送以避免重新加载页面?

After a user selects a file to upload, and presses the submit button, I am trying to get the file they selected from the file input tag above. How can I get the file with javascript so I can later send it by AJAX to avoid a page reload?

推荐答案

在没有iframe骇客的情况下,直到HTML5 File API出现之前,这是不可能的.使用HTML5 File API,您可以

This was not possible without iframe hacks until the advent of the HTML5 File API. Using the HTML5 File API, you can do

$(".input-file").change(function() {
    var file = this.files[0];
    var reader = new FileReader();
    reader.onload = function() {
        alert(reader.result);
    };
    reader.readAsText(file);
});

请注意,这仅适用于支持HTML5 File API的浏览器,例如Chrome.

Note that this will only work on browsers that support the HTML5 File API, such as Chrome.

这篇关于使用javascript获取文件输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆