一直对于上传文件到服务器端困惑;之前,如今,学到了关于WebClient的post知识web
瞬间对于上传文件到服务器以为好轻松;服务器
原理很简单;咱们经过post服务器的页面;把本地的文件直接传递过去;dom
如今,我有两个项目A(服务器端),B;post
我如今要把B的文件传递到A中;我在B用使用代码:blog
WebClient webclient = new WebClient();get
byte[] responseArray = webclient.UploadFile("http://localhost/ImageHandler.aspx ", "POST", @"" + fileName + "");string
string getPath = Encoding.GetEncoding("UTF-8").GetString(responseArray);it
这三段代码的意思很简单;主要是使用WebClient 的 post请求上传文件;io
webclient.UploadFile('post访问的路径', "POST",'文件的路径');class
只要咱们再A项目配置好ImageHandler.aspx;就能实现文件在服务器端处理;
A中ImageHandler.aspx代码
protected void Page_Load(object sender, EventArgs e) { try { foreach (string f in Request.Files.AllKeys) { string pathT = HttpRuntime.AppDomainAppPath.ToString() + "/images/"; string pathD = DateTime.Now.ToString("yyyyMMdd") + "/" + DateTime.Now.ToString("HHmm") + "/"; string sPath = pathT + pathD; if (!Directory.Exists(sPath)) { Directory.CreateDirectory(sPath); } HttpPostedFile file = Request.Files[f]; Random seed = new Random(); int randomNum =seed.Next(10,99); string fileName = DateTime.Now.ToString("HHmmss") + randomNum.ToString() + ".jpg"; file.SaveAs(sPath + fileName); Response.Write("http://..../images/" + pathD + fileName); } } catch (Exception ex) { Response.Write("error"); } Response.End(); }
上面代码很简明,咱们已经把file传递到服务器;只须要根据路径,把文件保存便可;