[ASP.net] HTML5 拖曳上傳檔案

2015-10-28

最近有需求透過拖曳上傳檔案簡單紀錄一下
image
1.接受端 risivajax.aspx  :


public partial class risivajax : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
        try
        {
            //如果src 有東西再進行處理
            if (!string.IsNullOrEmpty(Request["src"]))
            {
                var q = Request["src"].Substring(Request["src"].IndexOf(',') + 1);
 
                //將base 64 String 變成Image 物件
                var d = Base64ToImage(q);
                d.Save(AppDomain.CurrentDomain.BaseDirectory + "xxx.jpg");
            }
            else
            {
                Response.Write("error:null data");
            }
 
            Response.Write("success:");
        }
        catch (Exception err)
        {
            Response.Write("error:" + err.Message);
        }
 
 
 
    }
 
    public System.Drawing.Image Base64ToImage(string base64String)
    {
        byte[] imageBytes = Convert.FromBase64String(base64String);
        return BufferToImage(imageBytes);
    }
 
 
    private System.Drawing.Image BufferToImage(byte[] Buffer)
    {
        byte[] data = null;
        System.Drawing.Image oImage = null;
        MemoryStream oMemoryStream = null;
        Bitmap oBitmap = null;
        //建立副本
        data = (byte[])Buffer.Clone();
        try
        {
            oMemoryStream = new MemoryStream(data);
            //設定資料流位置
            oMemoryStream.Position = 0;
            oImage = System.Drawing.Image.FromStream(oMemoryStream);
            //建立副本
            oBitmap = new Bitmap(oImage);
        }
        catch
        {
            throw;
        }
        finally
        {
            oMemoryStream.Close();
            oMemoryStream.Dispose();
 
        }
        //return oImage;
        return oBitmap;
    }
 
}

其中,src 的 post data 專門接受base 64 string ,之後轉成 圖片後 存檔為 xxx.jpg
2. 發送端 .html , 透過這網站有 http://html5demos.com/file-api 可以拿到 h5utils.js 請自行引入 ,其中,負責傳送至 risivajax.aspx 的 ajax function 為


<script>
 
    var token = "";
    function PassImage(token, src, successFunc, failevent) {
        var $res;
        $.ajax({
            type: "POST",
            url: "risivajax.aspx",
            contentType: "application/x-www-form-urlencoded; charset=UTF-8",
            cache: false,
            dataType: 'text',
            data: "token=zxcadqwe&src=" + src,
            success: function (data) {
                if (data.indexOf('success') >= 0) {
                    $res = data.split(':');
                    alert(data);
                    if (successFunc != null) {
                        successFunc(data.d);
                    }
                }
                if (failevent != null) {
                    failevent(data.d);
                }
            },
            error: function () {
                if (failevent != null) {
                    failevent(data.d);
                }
            }
 
        });
        return $res;
    }
 
</script>

holder 的 ondrop 端為


holder.ondrop = function (e) {
     this.className = '';
     e.preventDefault();
 
     var file = e.dataTransfer.files[0];
     var reader = new FileReader();
 
     reader.onload = function (event) {
         document.getElementById('imgSample').src = event.target.result;
         console.log(event.target.result);
         PassImage(token, encodeURIComponent(event.target.result));            
     };
 
     console.log(file);
     reader.readAsDataURL(file);
 
     return false;
 };

範例下載: 載點
參考網站:
http://html5demos.com/file-api

http://www.dotblogs.com.tw/atowngit/archive/2010/01/13/13003.aspx




 


當麻許的超技八 2014 | Donma Hsu Design.