WebClient 上传文件 上传文件到服务器端

一直对于上传文件到服务器端困惑;以前,现在,学到了关于WebClient的post知识

瞬间对于上传文件到服务器觉得好轻松;

原理很简单;我们通过post服务器的页面;把本地的文件直接传递过去;

现在,我有两个项目A(服务器端),B;

我现在要把B的文件传递到A中;我在B用使用代码:

    WebClient webclient = new WebClient();

    byte[] responseArray = webclient.UploadFile("http://localhost/ImageHandler.aspx ", "POST", @"" + fileName + "");

    string getPath = Encoding.GetEncoding("UTF-8").GetString(responseArray);

  这三段代码的意思很简单;主要是使用WebClient 的 post请求上传文件;

  webclient.UploadFile('post访问的路径', "POST",'文件的路径');

只要我们再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传递到服务器;只需要根据路径,把文件保存即可;

   

原文地址:https://www.cnblogs.com/panshengqiang/p/3647018.html