gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 21:27:01 26 4
gpt4 key购买 nike

我正在尝试使用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>

并使用 jquery 表单插件:

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

结果:

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

alt text

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

我的问题:如何使用 iFrame 来实现“ajax 文件上传”。

注意:

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

谢谢

最佳答案

我会回答我的问题,我想我找到了解决方案。以下是我实现目标所遵循的步骤:

  1. 使form的属性“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>

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');
});

关于jquery - 如何使用 iframe 进行异步(AJAX)文件上传?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2909442/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com