javascript 在没有页面刷新的情况下以表单上传文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5638529/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:52:04  来源:igfitidea点击:

Uploading file in a form without page refresh

javascripthtmlajaxforms

提问by Mark

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?

现在我可以使用 Struts 上传文件,但它会刷新页面。如何在不刷新页面的情况下执行此操作?

回答by Ilia Koulikov

What worked for me:

什么对我有用:

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

在表单标签上,我有 target="hidden-iframe"

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

页面上隐藏的 i-frame 如下所示:

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

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

这里要强调的重要一点是表单引用的是框架的name属性而不是id

回答by Ramazan Polat

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

您可以使用 jQuery 发布表单并返回结果。

$('#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>

回答by Town

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

如果你可以使用 jQuery,你可以使用类似jQuery File Upload 的东西。

回答by HaleDeng

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.
  1. HTML5 支持文件 API。
  2. 创建一个隐藏的 iframe,将表单的属性 'target' 指向 iframe 的 id。