如何使用ajax提交文件上传表单? [英] How to submit file upload form with ajax?

查看:388
本文介绍了如何使用ajax提交文件上传表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Ajax文件上传


是否可以使用JQuery编写ajax请求提交一个文件字段的表单?我想这样做,因为通过这种方式,我可以让用户上传文件而不会离开当前页面。



我应该如何编写$ .ajax()调用?特别是我应该如何设置成ajax调用文件字段?编辑:我想只使用核心JQuery函数,没有插件。



感谢。

解决方案

为了与最广泛的浏览器保持兼容性,通过一个隐藏的iframe完成。



下面是一些示例代码,用于演示我的意思:

 < iframe name =my_iframeid =my_iframestyle =display:none;>< / iframe> 

< form action =/ next_step.phpmethod =posttarget =my_iframeentype =multipart / form-data>
< input type =filename =file_upload/>
< input type =buttonid =upload_btnvalue =上传文件/>

< label for =name>名称< / label>
< input type =textname =nameid =name/>

< input type =submitvalue =下一步/>
< / form>

< script type =text / javascript>
var btn = document.getElementById('upload_btn');
btn.onclick = function(){
var form_elem = document.forms [0];
//通过隐藏的iframe直接上传文件
form_elem.action ='/test_file.php';
form_elem.target ='my_iframe';

//提交表单
form_elem.submit();
};
< / script>

有些项目使得这更简单,例如 Plupload


Possible Duplicate:
Ajax file upload

Is it possible to write an ajax request with JQuery that "submits" a form with a file field? I want to do it because in this way i can make the user upload a file without leaving the current page.

How should i write the $.ajax() call? and in particular how should i set into the ajax call the file field?

EDIT: I'd like to use only core JQuery functions, without plugins.

Thanks.

解决方案

To maintain compatibility with the widest range of browsers this needs to be done through a hidden iframe.

Here is some sample code to demonstrate what I mean:

<iframe name="my_iframe" id="my_iframe" style="display: none;"></iframe>

<form action="/next_step.php" method="post" target="my_iframe" entype="multipart/form-data">
    <input type="file" name="file_upload" />
    <input type="button" id="upload_btn" value="Upload file" />

    <label for="name">Name</label>
    <input type="text" name="name" id="name" />

    <input type="submit" value="Next step" />
</form>

<script type="text/javascript">
    var btn = document.getElementById('upload_btn');
    btn.onclick = function(){
        var form_elem = document.forms[0];
        // direct file uploads through the hidden iframe
        form_elem.action = '/test_file.php';
        form_elem.target = 'my_iframe';

        // submit the form
        form_elem.submit();
    };
</script>

There are projects out there that make this easier such as Plupload

这篇关于如何使用ajax提交文件上传表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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