天天看點

使用jquery.form.js檔案進行檔案上傳

jquery.form.js,其ajaxSubmit()方法是專門為解決上傳問題而生的。

本想着檔案上傳是一件挺簡單的事,不過是擷取檔案位址儲存到伺服器而已,然而事實并非如此。

我信心滿滿的寫下input type="file",alert input 的value,打開頁面選擇了張圖檔,在擷取位址的時候,問題出現了,為什麼得到的位址是"C:\fakepath\*.jpg",帶着疑惑百度了一圈,原來這是浏覽器的安全機制,不讓擷取檔案的實體路徑,是以以假路徑代替。頓時信心銳減,出師不利啊,看來是輕敵了。

不過百度是個好老師,總能教給你解決問題的辦法,一番搜尋後,發現了一款上傳神器,jquery.form.js,其ajaxSubmit()方法是專門為解決上傳問題而生的。

下面就展示一下上傳的過程吧。

1.html源碼

要上傳圖檔,首先要把file放在form裡,異步送出表單,form中需要添加 method="post" enctype="multipart/form-data" 等屬性

使用jquery.form.js檔案進行檔案上傳
使用jquery.form.js檔案進行檔案上傳

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>upload</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
    <form id="uploadform" method="post" enctype="multipart/form-data">
    <input name="uploadimg" id="uploadimg" type="file" style="width: 100%" />
    </form>
    <img id="myimg" style="width: 80px; height: 80px;border:solid 1px #ccc; border-radius:40px; background-color:#ccc;" />
    
    <script type="text/javascript" src="js/jquery-1.4.1.js"></script>
    <script type="text/javascript" src="js/jquery.form.js"></script>
    <script type="text/javascript" src="js/upload.js"></script>
</body>
</html>      

View Code

2.Js檔案upload.js代碼

使用jquery.form.js檔案進行檔案上傳
使用jquery.form.js檔案進行檔案上傳
$(function () {
    //file内容改變觸發表單送出事件
    $("#uploadimg").change(function () {
        $("#uploadform").ajaxSubmit({
            url: "Upload.ashx?action=upload",
            type: "post",
            beforeSubmit: function () {
                $("#myimg").attr("src", "images/loading.gif");
            },
            success: function (url) {
                if (url) {
                    setTimeout(function () {
                        $("#myimg").fadeOut(1000, function () { 
                            $("#myimg").attr("src", url);
                        });
                        $("#myimg").fadeIn(1000);
                    }, 100);
                }
            }
        });
        return false;
    });
});      

3.一般處理程式Upload.ashx代碼

使用jquery.form.js檔案進行檔案上傳
使用jquery.form.js檔案進行檔案上傳
<%@ WebHandler Language="C#" Class="Upload" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

public class Upload : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/html"; //設定response的傳回值類型text/html,否則會自動加<pre>标簽
        string act = context.Request.QueryString["action"].ToString();

        switch (act)
        {
            case "upload":
                ImgUpload(context);
                break;
        }
    }

    /// <summary>
    /// 上傳圖檔至伺服器
    /// </summary>
    /// <param name="context"></param>
    public void ImgUpload(HttpContext context)
    {
        List<string> filelist = new List<string>();
        HttpFileCollection files = context.Request.Files;
        for (int i = 0; i < files.Count; i++)
        {
            string filename = System.IO.Path.GetFileName(files[i].FileName);
            filelist.Add(filename);
            string imgpath = "images\\upload\\";
            string bootpath = HttpRuntime.AppDomainAppPath + imgpath;
            string name = DateTime.Now.ToString("yyyy-MM-dd_HHmmss") + "_" + filename;
            if (!File.Exists(bootpath + name))
            {
                files[i].SaveAs(bootpath + name);
            }
            string localPath = imgpath + name;
            context.Response.Write(localPath);
            context.Response.End();
        }

    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}      

4.附上Demo

此demo是網站,下載下傳後釋出在iis或者建立個解決方案把它加進去就可以浏覽了。

https://files.cnblogs.com/Jackie-sky/Upload.rar

如果大家在上傳方面有其它的解決方法,望不吝賜教。