5

I have this bit of code:

<form name="myUploadForm" method="post" action="/scripts/upload.do" enctype="multipart/form-data" id="fileUpload">
   <table width="100%" border="0"> 
      <tr>
         <td>
            <input type="file" name="xlsFile" size="60" value="test.xls"> 
            <input type="button" value="Upload File" name="upload_xls">
         </td>
      </tr>
   </table>
</form>

Right now I can upload the file with Struts but it refreshes the page. How do I do this without the page refreshing?

Mark
  • 51
  • 1
  • 1
  • 2
  • possible dupe [ajax - How can I upload files asynchronously with JQuery? - Stack Overflow](http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously-with-jquery) – MikeM Apr 12 '11 at 16:32

4 Answers4

7

What worked for me:

On the form tag, I have target="hidden-iframe"

the hidden i-frame on the page looks like this:

<iframe name="hidden-iframe" style="display: none;"></iframe>

The important thing to underline here is that the form is referencing the name attribute of the frame and not the id.

justian17
  • 575
  • 1
  • 7
  • 17
5

You can post form with jQuery and get the result back.

$('#formId' ).submit(
    function( e ) {
        $.ajax( {
            url: '/upload',
            type: 'POST',
            data: new FormData( this ),
            processData: false,
            contentType: false,
            success: function(result){
                console.log(result);
                //$("#div1").html(str);
            }
        } );
        e.preventDefault();
    } 
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="formId" action="/upload" enctype="multipart/form-data" method="post">
        <input type="text" name="title"><br>
        <input type="file" name="upload" multiple="multiple"><br>
        <input type="submit" value="Upload">
</form>
<div id="div1">
</div>
ramazan polat
  • 7,111
  • 1
  • 48
  • 76
1

There are two methods:

  1. HTML5 supports File API.
  2. Create a hidden iframe, point the property 'target' of the form to the iframe's id.
Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
HaleDeng
  • 31
  • 4
0

If you can use jQuery, you can use something like jQuery File Upload.

Town
  • 14,706
  • 3
  • 48
  • 72