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

时间:2022-08-25 16:26:03

I'm trying to make ajax file upload . I read that it is not possible to do that without using iframe .
I wrote :

我想上传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>

and using jquery form plugin :

使用jquery表单插件:

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

The Result :

结果:

the file is uploaded successfully and I can see the uploaded file , but a dialog box appears :

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

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

since I send back a json result to display the file name + size etc ..

因为我返回一个json结果显示文件名+大小等。

My Question : How can I use the iFrame to be able to make " ajax file upload".

我的问题是:如何使用iFrame进行“ajax文件上传”。

Note:

注意:

  1. I don't prefer to use special plugin to upload file , if there is more appropriate/easier solutions.
  2. 如果有更合适/更简单的解决方案,我不喜欢使用特殊的插件来上传文件。
  3. I use jsp/servlets as a server-side language .. but I think it does not make sense which language I use .
  4. 我使用jsp/servlet作为服务器端语言。但是我认为我使用的语言是没有意义的。

Thanks

谢谢

2 个解决方案

#1


95  

I will answer my question , I think I found the solution. These are the steps that I followed to achieve the goal :

我会回答我的问题,我想我找到了答案。以下是我为实现目标所采取的步骤:

  1. Make the attribute "target" of the form point to " iframe " .
  2. 使表单的属性“目标”指向“iframe”。
  3. Use a normal HTML request ( not Asynchronous/Ajax request ) to submit the form.
  4. 使用普通的HTML请求(不是异步/Ajax请求)提交表单。
  5. Because the target frame is iframe , the whole page will not be refreshed - just the iframe.
  6. 因为目标帧是iframe,所以整个页面不会刷新——只是iframe。
  7. 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.
  8. 一旦iframe onload事件发生(使用Javascript捕获该事件),然后执行您想要的操作,例如,您可以返回一个请求来列出最近上传的文件信息。

The final code looks like this:

最后的代码是这样的:

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

#2


4  

This example taken from BugKiller. complete working example which allows you to upload a logo and see it immediately in the html page, following which the upload value gets cleared:

这个例子来自BugKiller。完整的工作示例,允许您上传一个徽标,并立即在html页面中看到它,随后上传的值将被清除:

html:

html:

<form id="uploadForm" method="post" enctype="multipart/form-data"  target="uploadTrg">
  <div id="fileUploadWrapper"><input type="file" name="file" id="fileUpload"></div>
  <input type="submit" value="Upload" id="submitBtn"/>
</form>
<iframe id="uploadTrg" name="uploadTrg" height="0" width="0" frameborder="0" scrolling="no" style="display:none"></iframe>
<img id="imgLogo" style="border-width:0px;" />

javascript:

javascript:

$(document).ready(function () {
  var companynumber = '12345'; //get this from the database
  var logoUploadUrl = 'UploadHandler.aspx?logoupload=true&companynumber=' + companynumber ;
  $("#uploadForm").attr("action", logoUploadUrl);

  $("#uploadTrg").load(function () {
    //upload complete

    //only way to reset contents of file upload control is to recreate it
    $("#fileUploadWrapper").html('<input type="file" name="file" id="fileUpload">');

    //reload the logo url, add ticks on the end so browser reloads it
    var ticks = ((new Date().getTime() * 10000) + 621355968000000000);
    var logoUrl = 'images/clients/' + companynumber + '/client.gif?' + ticks;
    $("#imgLogo").attr('src', logoUrl);
  });
});

upload handler code behind (C#):

上传处理程序代码后(c#):

namespace MyWebApp {
    public partial class UploadHandler : System.Web.UI.Page {

        protected void Page_Load(object sender, EventArgs e) {
          if (Request.Params["logoupload"] != null) {
            string companynumber = Request.Params["companynumber"];
            string savePath = Server.MapPath("\\images") + "\\clients\\" + companynumber + "\\client.gif";
            if (File.Exists(savePath))
                File.Delete(savePath);
            //save the file to the server 
            Request.Files[0].SaveAs(savePath);

            Response.Write("OK");
            Response.Flush();
            Response.End();
          }
       }
}

#1


95  

I will answer my question , I think I found the solution. These are the steps that I followed to achieve the goal :

我会回答我的问题,我想我找到了答案。以下是我为实现目标所采取的步骤:

  1. Make the attribute "target" of the form point to " iframe " .
  2. 使表单的属性“目标”指向“iframe”。
  3. Use a normal HTML request ( not Asynchronous/Ajax request ) to submit the form.
  4. 使用普通的HTML请求(不是异步/Ajax请求)提交表单。
  5. Because the target frame is iframe , the whole page will not be refreshed - just the iframe.
  6. 因为目标帧是iframe,所以整个页面不会刷新——只是iframe。
  7. 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.
  8. 一旦iframe onload事件发生(使用Javascript捕获该事件),然后执行您想要的操作,例如,您可以返回一个请求来列出最近上传的文件信息。

The final code looks like this:

最后的代码是这样的:

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

#2


4  

This example taken from BugKiller. complete working example which allows you to upload a logo and see it immediately in the html page, following which the upload value gets cleared:

这个例子来自BugKiller。完整的工作示例,允许您上传一个徽标,并立即在html页面中看到它,随后上传的值将被清除:

html:

html:

<form id="uploadForm" method="post" enctype="multipart/form-data"  target="uploadTrg">
  <div id="fileUploadWrapper"><input type="file" name="file" id="fileUpload"></div>
  <input type="submit" value="Upload" id="submitBtn"/>
</form>
<iframe id="uploadTrg" name="uploadTrg" height="0" width="0" frameborder="0" scrolling="no" style="display:none"></iframe>
<img id="imgLogo" style="border-width:0px;" />

javascript:

javascript:

$(document).ready(function () {
  var companynumber = '12345'; //get this from the database
  var logoUploadUrl = 'UploadHandler.aspx?logoupload=true&companynumber=' + companynumber ;
  $("#uploadForm").attr("action", logoUploadUrl);

  $("#uploadTrg").load(function () {
    //upload complete

    //only way to reset contents of file upload control is to recreate it
    $("#fileUploadWrapper").html('<input type="file" name="file" id="fileUpload">');

    //reload the logo url, add ticks on the end so browser reloads it
    var ticks = ((new Date().getTime() * 10000) + 621355968000000000);
    var logoUrl = 'images/clients/' + companynumber + '/client.gif?' + ticks;
    $("#imgLogo").attr('src', logoUrl);
  });
});

upload handler code behind (C#):

上传处理程序代码后(c#):

namespace MyWebApp {
    public partial class UploadHandler : System.Web.UI.Page {

        protected void Page_Load(object sender, EventArgs e) {
          if (Request.Params["logoupload"] != null) {
            string companynumber = Request.Params["companynumber"];
            string savePath = Server.MapPath("\\images") + "\\clients\\" + companynumber + "\\client.gif";
            if (File.Exists(savePath))
                File.Delete(savePath);
            //save the file to the server 
            Request.Files[0].SaveAs(savePath);

            Response.Write("OK");
            Response.Flush();
            Response.End();
          }
       }
}