萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery ajaxfileupload.js 非同步上傳檔案完整實作

ajaxfileupload.js 是輕量級 jQuery 非同步上傳插件,無需 Flash,透過隱藏 iframe 模擬 AJAX。本文提供前端 HTML/JS、後端 ASP.NET (ashx) 完整代碼。

前置準備

  • 引入 jquery-2.1.1.js 與 ajaxfileupload.js

HTML

<input id="fileToUpload" type="file" name="fileToUpload">

JavaScript

function saveCInfo() {
    var filename = document.getElementById("fileToUpload").value;
    if (filename != "") {
        $.ajaxFileUpload({
            url: '../Order/OrderExec.ashx?oprMode=fileUpload' +
                 "&filename=" + filename +
                 "&billno=" + billno +
                 "&companyname=" + companyname,
            secureuri: false,
            fileElementId: 'fileToUpload', // 上傳控件 ID
            // dataType: 'json',
            error: function() { alert('error'); },
            success: function(datax) {
                if (datax != "") {
                    msgShow('系統提示', '上傳成功!', 'info');
                } else {
                    msgShow('系統提示', '上傳失敗!', 'info');
                }
            }
        });
    } else {
        $.messager.alert('提示', '請選擇上傳檔案', 'info');
    }
}

後端 OrderExec.ashx

public void FileUpload(HttpContext context) {
    try {
        context.Response.ContentType = "text/html";
        string companyname = context.Request.Params["companyname"];
        string billno = context.Request.Params["billno"];
        string filename = context.Request.Params["filename"];
        string name = companyname + "_" + billno + "_" + filename;

        HttpFileCollection files = HttpContext.Current.Request.Files;
        string savePath = context.Server.MapPath("~/upload/");
        if (!System.IO.Directory.Exists(savePath))
            System.IO.Directory.CreateDirectory(savePath);

        savePath += name;
        files[0].SaveAs(savePath);
        context.Response.Write(savePath);
    } catch (Exception ex) {
        context.Response.Write("FileUpload: " + ex.Message);
    }
}

關鍵參數說明

  • fileElementId:<input type="file"> 的 id 屬性
  • url:可攜帶查詢字串傳遞額外參數
  • secureuri:是否 HTTPS,通常 false
  • dataType:預期回應格式(json/xml/html/script)
copyright © 萬盛學電腦網 all rights reserved