Uploading file in a form without page refresh

16,467

Solution 1

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.

Solution 2

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>

Solution 3

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.
Share:
16,467
Admin
Author by

Admin

Updated on June 23, 2022

Comments

  • Admin
    Admin almost 2 years

    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?

  • FlorianB
    FlorianB over 7 years
  • lurker
    lurker about 5 years
    @FlorianB that blog is dated 2008. (And, I know, your comment is dated 2016!)