如何使用iframe进行异步(AJAX)文件上传?

Abd*_*lah 50 ajax jquery servlets file-upload

我正在尝试上传ajax文件.我读到如果不使用它就不可能做到这一点iframe.
我写 :

<iframe id="uploadTrg" name="uploadTrg" height="0" width="0" frameborder="0" scrolling="yes"></iframe>
<form id="myForm" action="file-component" method="post" enctype="multipart/form-data"  target="uploadTrg">
File: <input type="file" name="file">
<input type="submit" value="Submit" id="submitBtn"/>
</form>
Run Code Online (Sandbox Code Playgroud)

并使用jquery表单插件:

$('#myForm').ajaxForm({
    dataType:  'json',
    success:   function(data){
        alert(data.toSource());
    }
});
Run Code Online (Sandbox Code Playgroud)

结果 :

文件上传成功,我可以看到上传的文件,但会出现一个对话框:

替代文字

因为我发回一个json结果来显示文件名+大小等.

我的问题: 如何使用iFrame进行"ajax文件上传".

注意:

  1. 如果有更合适/更简单的解决方案,我不喜欢使用特殊插件上传文件.
  2. 我使用jsp/servlets作为服务器端语言..但我认为使用哪种语言没有意义.

谢谢

Abd*_*lah 95

我会回答我的问题,我想我找到了解决方案.这些是我为实现目标而采取的步骤:

  1. 使表单的属性" target " 为" iframe ".
  2. 使用普通的HTML请求(而不是异步/ Ajax请求)来提交表单.
  3. 由于目标框架是iframe,因此不会刷新整个页面 - 只是iframe.
  4. iframe onload事件发生后(使用Javascript捕获该事件)然后执行您想要的操作,例如,您可以发回请求以列出最近上传的文件信息.

最终代码如下所示:

    <!-- Attach a file -->

    <iframe id="uploadTrg" name="uploadTrg" height="0" width="0" frameborder="0" scrolling="yes"></iframe>

    <form id="myForm" action="http://example.com/file-upload-service" method="post" enctype="multipart/form-data"  target="uploadTrg">

        File: <input type="file" name="file">
        <input type="submit" value="Submit" id="submitBtn"/>

    </form>

    <div id="ajaxResultTest"></div>
Run Code Online (Sandbox Code Playgroud)

javascript:

$("iframe").load(function(){
    // ok , now you know that the file is uploaded , you can do what you want , for example tell the user that the file is uploaded 
    alert("The file is uploaded");

    // or you can has your own technique to display the uploaded file name + id ? 
    $.post('http://example.com/file-upload-service?do=getLastFile',null,function(attachment){

       // add the last uploaded file , so the user can see the uploaded files
       $("#ajaxResultTest").append("<h4>" + attachment.name + ":" + attachment.id "</h4>");

    },'json');
});
Run Code Online (Sandbox Code Playgroud)

  • 不推荐使用target属性(http://www.w3schools.com/TAGS/att_form_target.asp).我开始相信必须使用弃用的(X)HTML或Flash /等.完成什么/应该/非常原始的功能. (5认同)
  • @SpainTrain HTML5支持目标属性.;) (3认同)
  • 很好的解释.但是,您可以在iframe内容中回显响应,然后在js中读取它,而不是制作另一个ajax帖子 (2认同)