一聚教程网:一个值得你收藏的教程网站

热门教程

ASP.NET中利用WebClient上传图片到远程服务的方法

时间:2022-06-25 06:00:45 编辑:袖梨 来源:一聚教程网

一、客户端

1.页面

 

 代码如下复制代码
"Form1" method="post" runat="server" enctype="multipart/form-data">
    "MyFile" type="file" runat="server" />
    
    
    "Button1" runat="server" Text="上载文件" OnClick="Button1_Click">
  

 

2.后台

 

 代码如下复制代码

System.Web.HttpFileCollection oFiles = System.Web.HttpContext.Current.Request.Files;

   stringFilePath = oFiles[0].FileName;

   stringFileName = FilePath.Substring(FilePath.LastIndexOf("\") + 1);

   byte[] b =newbyte[oFiles[0].ContentLength];

   System.IO.Stream fs = (System.IO.Stream)oFiles[0].InputStream;

   fs.Read(b, 0, oFiles[0].ContentLength);

   stringpostData ="data="+ HttpUtility.UrlEncode(Convert.ToBase64String(b));

   var webclient =newWebClient();

   webclient.Headers.Add("Content-Type","application/x-www-form-urlencoded");

   byte[] byteArray = Encoding.UTF8.GetBytes(postData);

   //byte[] buffer = webclient.UploadData("http://localhost/datapush/DataPush.ashx", "POST", byteArray);//ashx

   byte[] buffer = webclient.UploadData("http://localhost/datapush/WebServiceDataPush.asmx/DataPush","POST", byteArray);//asmx

   var msg = Encoding.UTF8.GetString(buffer);

   Response.Write(msg);

 

二、服务端

 

 代码如下复制代码

stringmsg ="";

   byte[] filedata = Convert.FromBase64String(context.Request["data"]);

   if(filedata.Length == 0)

   {

    msg="{"code":"上传的是空文件"}";

   }

   if(filedata.Length > 1048576)

   {

    msg ="{"code":"图片大小不能超过1M"}";

   }

   stringfileextension = filedata[0].ToString() + filedata[1].ToString();

   if(fileextension =="7173")

   {

    fileextension ="gif";

   }

   elseif(fileextension =="255216")

   {

    fileextension ="jpg";

   }

   elseif(fileextension =="13780")

   {

    fileextension ="png";

   }

   elseif(fileextension =="6677")

   {

    fileextension ="bmp";

   }

   elseif(fileextension =="7373")

   {

    fileextension ="tif";

   }

   else

   {

    msg ="{"code":"上传的文件不是图片"}";

   }

   try

   {

    //保存图片

    stringfilename = Guid.NewGuid().ToString("D") +"."+ fileextension;

    System.IO.MemoryStream ms =newSystem.IO.MemoryStream(filedata);

    System.IO.FileStream fs =newSystem.IO.FileStream(context.Server.MapPath("~/") +"/采集图片/"+ filename, System.IO.FileMode.Create);

    ms.WriteTo(fs);

    ms.Close();

    fs.Close();

    fs =null;

    ms =null;

    msg ="{"code":"上传图片成功"}";

   }

   catch(Exception exe)

   {

    msg ="{"code":""+ exe.Message +""}";

   }

 

热门栏目