Jquery實現異步上傳圖片


利用jQuery的ajax函數就可以實現異步上傳圖片了。一開始我是想在處理程序中,直接用context.Request.Files來獲取頁面中的input file,但是不知道為什么一次獲取不了。網上說的,Form中要設置enctype="multipart/form-data"和 method="post",input file中要加runat="server",但都加了依然獲取不到。哪位大俠知道的,求指教啊。

既然后台獲取不到Input file怎么辦呢。其實我們上傳文件,主要是獲取到文件的物理地址就行了。只要有了這個文件地址就可以用bitmap獲取到這個圖片了。

剛開始我是想用ajax GET來傳送地址,但TMD如果文件名有中文就亂碼了。好在后面改成POST后就可以成功傳送了。

話不多說,上代碼:

前台:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <script src="Scripts/jquery-1.3.2-vsdoc2.js" type="text/javascript"></script>
    <script type="text/javascript">
        function uploadImage() {
        //判斷是否有選擇上傳文件
            var imgPath = $("#uploadFile").val();
            if (imgPath == "") {
                alert("請選擇上傳圖片!");
                return;
            }
            //判斷上傳文件的后綴名
            var strExtension = imgPath.substr(imgPath.lastIndexOf('.') + 1);
            if (strExtension != 'jpg' && strExtension != 'gif'
            && strExtension != 'png' && strExtension != 'bmp') {
                alert("請選擇圖片文件");
                return;
            }
            $.ajax({
                type: "POST",
                url: "handler/UploadImageHandler.ashx",
                data: { imgPath: $("#uploadFile").val() },
                cache: false,
                success: function(data) {
                    alert("上傳成功");
                    $("#imgDiv").empty();
                    $("#imgDiv").html(data);
                    $("#imgDiv").show();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert("上傳失敗,請檢查網絡后重試");
                }
            });
        }
    </script>
</head>
<body>
<form  enctype="multipart/form-data" method="post">
<input type="file" id="uploadFile" runat="server" />
<input type="button" id="btnUpload" value="確定" onclick="uploadImage()" />
<div id="imgDiv">
</div>
</form>
</body>
</html>

后台中的ashx:

    public void ProcessRequest (HttpContext context) {
        //不知道為什么獲取不到
        //HttpPostedFile file = context.Request.Files["userFile"];
        string filePath = context.Request["imgPath"];
        string path = "UploadImgs\\";
        Bitmap map = new Bitmap(filePath);
        string fileName = Path.GetFileName(filePath);
        string mapPath = context.Server.MapPath("~");
        string savePath = mapPath + "\\" + path + fileName;
        map.Save(savePath);
        //上傳成功后顯示IMG文件
        StringBuilder sb = new StringBuilder();
        sb.Append("<img id=\"imgUpload\" src=\""+path.Replace("\\","/")+fileName+"\" />");
        context.Response.Write(sb.ToString());
        context.Response.End();
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

出處:http://blog.csdn.net/highplayer/article/details/7392337#html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM