DIV CSS 佈局教程網

AjaxFileUpload 外掛實作無刷新檔案上傳(含常見錯誤排除)
編輯:JQuery特效代碼     

jQuery 的 AjaxFileUpload 外掛可以在不重整頁面的情況下上傳檔案。原理是在背後動態建立一個隱藏 iframe 與表單,藉此繞開 XMLHttpRequest 無法傳送檔案的限制。以下說明用法、參數與常見錯誤。

一、引入檔案

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="ajaxfileupload.js"></script>

二、HTML 結構

<img id="loading" src="loading.gif" style="display:none;" />
<input id="fileToUpload" type="file" size="20" name="fileToUpload" class="input" />
<button class="button" id="buttonUpload" onclick="return ajaxFileUpload();">上傳</button>

只需要三個元素:等待提示圖、檔案選擇框、觸發按鈕。不需要自己寫 form——外掛會自動產生提交用的表單。這點是它比其他上傳方案輕量的主要原因。

要注意的是,fileElementId 參數取的是檔案域的 id,而後端要讀取檔案資訊時用的是 name,兩者不可混淆。

三、JavaScript 部分

<script type="text/javascript">
function ajaxFileUpload(){
    loading();   // 啟動等待提示

    $.ajaxFileUpload({
        url           : 'upload.php',   // 處理上傳的後端路徑
        secureuri     : false,          // 是否啟用安全提交
        fileElementId : 'fileToUpload', // 檔案域的 id
        dataType      : 'json',         // 回傳資料格式
        success: function (data, status){
            if (typeof(data.error) != 'undefined'){
                if (data.error != ''){
                    alert(data.error);
                } else {
                    alert(data.msg);
                }
            }
        },
        error: function (data, status, e){
            alert(e);
        }
    });
    return false;
}

function loading(){
    $("#loading").ajaxStart(function(){
        $(this).show();
    }).ajaxComplete(function(){
        $(this).hide();
    });
}
</script>

參數速查

url:處理上傳的程式路徑,建議先在瀏覽器直接拜訪確認可連。
fileElementId:檔案輸入域的 id。
secureuri:是否啟用安全提交,預設 false。
dataType:回傳資料型別,一般用 json。
success / error:成功與失敗的回呼函式。

四、常見錯誤與對應原因

SyntaxError: missing ; before statement — 多半是 url 路徑不對或無法存取。
SyntaxError: syntax error — 檢查後端程式本身是否有語法錯誤。
SyntaxError: invalid property id — 屬性 id 名稱寫錯或不存在。
SyntaxError: missing } in XML expression — 檔案域 name 前後不一致。
其他自定義錯誤 — 直接把回傳內容用 alert 印出來看,比猜錯誤訊息快得多。

這些錯誤訊息之所以難懂,是因為 iframe 上傳拿到的是字串而非真正的 JSON,一旦格式不合法就會落到 JavaScript 的解析錯誤上。因此後端回應務必是格式正確的 JSON,且不要輸出任何多餘的內容(包含 BOM 與空白)。

五、後端範例

.NET 端:

public partial class web_ajax_FileUpload : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpFileCollection files = HttpContext.Current.Request.Files;
        files[0].SaveAs("d:/adw.jpg");

        Response.Write("{");
        Response.Write("msg:'a',");
        Response.Write("error:''");
        Response.Write("}");
        Response.End();
    }
}

Java(Struts)端:

public class UpdateAction extends DispatchAction {
    public ActionForward uploader(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
        UpFormForm upFormForm = (UpFormForm) form;
        FormFile ff = upFormForm.getHouseMaps();
        try {
            InputStream is = ff.getInputStream();
            File file = new File("D:/" + ff.getFileName());
            OutputStream os = new FileOutputStream(file);
            byte[] b = new byte[1024];
            int len = 0;
            while ((len = is.read(b)) != -1) {
                os.write(b, 0, len);
            }
            os.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

安全提醒

上傳功能是最容易被利用的入口之一。後端務必檢查副檔名與實際 MIME 型別、限制檔案大小、重新命名儲存檔名(避免直接使用使用者提供的檔名,以免路徑穿越),並將上傳目錄排除在可執行範圍之外。範例中的 ff.getFileName() 直接拼接路徑,正式環境請勿照抄。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved