如何使用 iframe 进行异步(AJAX)文件上传? [英] How to make Asynchronous(AJAX) File Upload using iframe?
问题描述
我正在尝试上传 ajax 文件.我读到如果不使用 iframe
就不可能做到这一点.
我写道:
I'm trying to make ajax file upload . I read that it is not possible to do that without using iframe
.
I wrote :
<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>
并使用 jquery 表单插件:
and using jquery form plugin :
$('#myForm').ajaxForm({
dataType: 'json',
success: function(data){
alert(data.toSource());
}
});
结果:
文件上传成功,我可以看到上传的文件,但是出现一个对话框:
the file is uploaded successfully and I can see the uploaded file , but a dialog box appears :
因为我发回一个json结果来显示文件名+大小等..
since I send back a json result to display the file name + size etc ..
我的问题:我怎样才能使用 iFrame 来制作 "ajax文件上传".
My Question : How can I use the iFrame to be able to make " ajax file upload".
注意:
- 如果有更合适/更简单的解决方案,我不喜欢使用特殊插件来上传文件.
- 我使用 jsp/servlets 作为服务器端语言 .. 但我认为我使用哪种语言没有意义.
谢谢
推荐答案
我会回答我的问题,我想我找到了解决方案.这些是我为实现目标而遵循的步骤:
I will answer my question , I think I found the solution. These are the steps that I followed to achieve the goal :
- 使表单的属性目标"指向iframe".
- 使用普通的 HTML 请求(不是异步/Ajax 请求)提交表单.
- 因为目标框架是 iframe ,所以不会刷新整个页面——只刷新 iframe.
- 一旦 iframe onload 事件发生(使用 Javascript 捕获该事件)然后做你想做的事,例如您可以发回请求以列出最近上传的文件信息.
- Make the attribute "target" of the form point to " iframe " .
- Use a normal HTML request ( not Asynchronous/Ajax request ) to submit the form.
- Because the target frame is iframe , the whole page will not be refreshed - just the iframe.
- Once iframe onload event happens (capture that event using Javascript) then do what you want, e.g. You can send back a request to list recent uploaded file info.
最终代码如下:
<!-- 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>
javascript:
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');
});
这篇关于如何使用 iframe 进行异步(AJAX)文件上传?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!