简体   繁体   English

使用ajax帖子上传文件而不刷新页面

[英]Upload files without refreshing the page by using ajax post

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: 我有两个问题:

  1. The moment I select some files, ie the onchange event of the input type file , the file(s) should get uploaded. 我选择一些文件的那一刻,即input类型fileonchange事件,应该上传文件。

    I have a Java page that receives multipart request parameter and uploads the file to the said location. 我有一个Java页面,它接收多部分请求参数并将文件上传到所述位置。 My problem is the form submission onchange , so that the Java file can proceed with further operations. 我的问题是表单提交onchange ,以便Java文件可以继续进行进一步的操作。

    I googled and went through lot of articles. 我用Google搜索并浏览了大量文章。 Some say it's not possible to upload files directly via Ajax, some say submit the form to an iframe via Ajax/jQuery. 有人说不可能通过Ajax直接上传文件,有人说通过Ajax / jQuery将表单提交给iframe。

    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. 但无法获得预期的结果。

  2. I also need a progress bar for the upload operation. 我还需要一个上传操作的进度条。

Look at this example using an IFrame, is in PHP but changing the action should do the trick 使用IFrame查看此示例,在PHP中,但更改操作应该可以解决问题

Ajax Style File Uploading Using Hidden IFrame 使用隐藏IFrame上传Ajax样式文件

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 example on its website available that shows how to display a progress bar. 其网站上有一个示例 ,显示如何显示进度条。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM