简体   繁体   中英

Upload files without refreshing the page by using ajax post

I have a page file-upload.jsp with the code snippet below:

 <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.

    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.

  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

Ajax Style File Uploading Using Hidden IFrame

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.

There is an example on its website available that shows how to display a progress bar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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