javascript 使用ajax post上传文件而不刷新页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17970729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Upload files without refreshing the page by using ajax post
提问by Cyber Dude
I have a page file-upload.jsp with the code snippet below:
我有一个页面 file-upload.jsp,其代码片段如下:
<form action="" id="frmupload" name="frmupload" method="post" enctype="multipart/form-data">
<input type="file" id="upload_file" name="upload_file" multiple="" />
<input type="submit" value="Update" />
</form>
I have 2 questions:
我有两个问题:
The moment I select some files, i.e the
onchange
event of theinput
typefile
, the file(s) should get uploaded.I have a Java page that receives multipart request parameter and uploads the file to the said location. My problem is the form submission
onchange
, so that the Java file can proceed with further operations.I googled and went through lot of articles. Some say it's not possible to upload files directly via Ajax, some say submit the form to an iframe via Ajax/jQuery.
I tried a lot of code from internet, such as this:
$(document).ready(function(){ $('upload_file').change(function(){ var data = new FormData(); data.append('file', $(this[0].files[0])); $.ajax({ url: 'photo.jsp', type: 'post', contentType: attr('enctype', "multipart/form-data"), data: data, success: function(data){ alert(data); } }) }); });
but could not get the expected results.
I also need a progress bar for the upload operation.
我选择一些文件的那一刻,即类型的
onchange
事件,文件应该被上传。input
file
我有一个 Java 页面,它接收多部分请求参数并将文件上传到上述位置。我的问题是表单提交
onchange
,以便Java文件可以进行进一步的操作。我用谷歌搜索并浏览了很多文章。有人说不可能通过 Ajax 直接上传文件,有人说通过 Ajax/jQuery 将表单提交到 iframe。
我从互联网上尝试了很多代码,例如:
$(document).ready(function(){ $('upload_file').change(function(){ var data = new FormData(); data.append('file', $(this[0].files[0])); $.ajax({ url: 'photo.jsp', type: 'post', contentType: attr('enctype', "multipart/form-data"), data: data, success: function(data){ alert(data); } }) }); });
但未能得到预期的结果。
我还需要一个上传操作的进度条。
回答by Daniele
Look at this example using an IFrame, is in PHP but changing the action should do the trick
看看这个使用 IFrame 的例子,在 PHP 中,但改变动作应该可以解决问题
回答by mthmulders
Since you're already using jQuery, I would definitely go for the jQuery Form Plugin, which allows you to do form uploads via AJAX, even if the form contains a file
input.
由于您已经在使用 jQuery,我肯定会选择jQuery Form Plugin,它允许您通过 AJAX 进行表单上传,即使表单包含file
输入。
There is an exampleon its website available that shows how to display a progress bar.
其网站上有一个示例,显示了如何显示进度条。
回答by Mitesh Jain
Look at this example it is exact as you want
看看这个例子,它完全符合你的要求
http://www.asp.net/ajaxlibrary/ajaxcontroltoolkitsamplesite/asyncfileupload/asyncfileupload.aspx
http://www.asp.net/ajaxlibrary/ajaxcontroltoolkitsamplesite/asyncfileupload/asyncfileupload.aspx