[Xamarin] 上傳檔案/圖片 到Server 端 (Server 接檔案端)
2015-08-25
蠻常會用到的就是上傳檔案/圖片到Server端,所以筆記一下,首先筆記一下Server Site 的Code
首先開的檔案是 risivfile.ashx
開啟檔案後就是Code 的部分,下面的Code 我已經盡量精簡化,簡單的說就是會把收到的東西存成sample.jpg
C# code:
using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Web;namespace TestUpload1{ /// <summary> /// Summary description for RisivFile /// </summary>public class RisivFile : IHttpHandler
{public void ProcessRequest(HttpContext context)
{ try { if (context.Request.ContentLength > 0) { using (FileStream fs =
File.Create((AppDomain.CurrentDomain.BaseDirectory + "sample.jpg"))) {SaveFile(context.Request.InputStream, fs);
}
//成功 context.Response.Write("success");}
else { //無檔案 context.Response.Write("fail:no file");}
}
catch (Exception ex) { //意外得失敗 context.Response.Write("fail:" + ex.Message);}
}
private void SaveFile(Stream stream, FileStream fs)
{ try {byte[] buffer = new byte[4096];
int bytesRead; while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0) {fs.Write(buffer, 0, bytesRead);
}
}
catch (Exception ex) {}
}
public bool IsReusable
{get
{return false;
}
}
}
}
這樣Server site 得部分就完成了.. 再來就是 client 的部分..
