1. 程式人生 > >ajaxFileUpload 非同步上傳圖片 使用說明

ajaxFileUpload 非同步上傳圖片 使用說明

首先引入 相應的jquery

<script src="script/jquery-1.7.1.min.js"></script>
    <script src="script/ajaxfileupload.js"></script>

ajaxFileUpload 使用說明

$.ajaxFileUpload({
    url: 'PhotoGet.ashx',//執行上傳處理的檔案地址
    secureuri: false,//是否加密,一般是false,預設值為false
    fileElementId: 'UpImg1',//<input type="file" id="UpImg1" name="UpImg1"/> 這裡的fileElementId 屬性值必須和id是一樣的並且要求這個控制元件要有name屬性,用於在伺服器端接收
    data: {//額外傳遞的資料,使用json,此時必須設定type為post
        type:1
    },
    type:'post',//請求方式,如果傳遞額外資料,必須是post
    success: function (data){//成功的回撥函式,內部處理會加上html標籤
        //因返回的data 是dom物件需轉換成jquery物件才能獲取到對應的相對路徑
        $("#img1").attr("src", $(data).text());
    }
});

前段其他程式碼

<body>
     <input type="file" id="UpImg1" name="UpImg1" />
    <input type="button" id="btnUpload" value="上傳" />
    <br/>
    <img id="img1" src="" />

</body>

伺服器端程式碼

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

namespace WebUI
{
    /// <summary>
    /// PhotoGet 的摘要說明
    /// </summary>
    public class PhotoGet : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
        
            context.Response.ContentType = "text/plain";
           //獲取要儲存的檔案
            HttpPostedFile file = context.Request.Files["UpImg1"];
            //儲存檔案的相對檔案路徑
            string path1 = "/loadimg/" + file.FileName;
            //把相對檔案路徑轉換成絕對檔案路徑
            string path2 = context.Server.MapPath(path1);
            //儲存傳的檔案
            file.SaveAs(path2);
            //返回儲存檔案的相對路徑
            context.Response.Write(path1);
        }

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