簡體   English   中英

如何使用iframe進行異步(AJAX)文件上傳?

[英]How to make Asynchronous(AJAX) File Upload using iframe?

我正在嘗試上傳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());
    }
});

結果 :

文件上傳成功,我可以看到上傳的文件,但會出現一個對話框:

替代文字

因為我發回一個json結果來顯示文件名+大小等。

我的問題:如何使用iFrame進行“ajax文件上傳”。

注意:

  1. 如果有更合適/更簡單的解決方案,我不喜歡使用特殊插件上傳文件。
  2. 我使用jsp / servlets作為服務器端語言..但我認為使用哪種語言沒有意義。

謝謝

我會回答我的問題,我想我找到了解決方案。 這些是我為實現目標而采取的步驟:

  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>

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

這個例子取自BugKiller。 完整的工作示例,允許您上傳徽標並立即在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的:

$(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);
  });
});

上傳處理程序代碼(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();
          }
       }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM