zl程序教程

您现在的位置是:首页 >  后端

当前栏目

c#批量上传图片到服务器示例分享

c#批量上传服务器 示例 分享 图片
2023-06-13 09:15:19 时间

客户端代码:

复制代码代码如下:


///<summary>
///批量上传图片
///</summary>
///<paramname="srcurl">服务器路径</param>
///<paramname="imagesPath">图片文件夹路径</param>
///<paramname="files">图片名称</param>
publicvoidUpLoadFile(stringsrcurl,stringimagesPath,List<string>files)
{
   intcount=1;
   foreach(stringimageNameinfiles)
   {
stringname=imageName;
stringurl=null;
//+ 加号特殊处理
if(name.Contains("+"))
{
   url=srcurl+"name="+name.Replace("+","%2B");
}
else
{
   url=srcurl+"name="+name;
}

FileStreamfs=newFileStream(imagesPath+name,FileMode.Open);
byte[]data=newbyte[fs.Length];
fs.Read(data,0,data.Length);
fs.Close();

HttpWebRequestrequest=(HttpWebRequest)WebRequest.Create(url);
request.ContentType="image/jpeg";
request.Method="POST";
Encodingencoding=Encoding.UTF8;
request.ContentLength=data.Length;
StreamrequestStream=request.GetRequestStream();
requestStream.Write(data,0,data.Length);
requestStream.Close();


HttpWebResponseresponse=(HttpWebResponse)request.GetResponse();
StreamReaderstreamReader=newStreamReader(response.GetResponseStream(),encoding);
stringretString=streamReader.ReadToEnd();
streamReader.Close();

Console.WriteLine((count++)+"/"+files.Count);

   }
}

服务器端代码:

复制代码代码如下:


usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Net;
usingSystem.Text;
usingSystem.IO;

publicpartialclassupload:System.Web.UI.Page
{

protectedvoidPage_Load(objectsender,EventArgse)
{
stringfPath=Server.MapPath("服务器端图片存储的虚拟目录名称");//得到虚拟目录的真实路径//检查存储目录
if(!Directory.Exists(fPath))
{
   Directory.CreateDirectory(fPath);
}
stringname=Request.QueryString["name"];//得到文件名
HttpUtility.UrlEncode(name,Encoding.GetEncoding("UTF-8"));

if(name!=null)
{
   if(!File.Exists(fPath+name))
   {
System.IO.Streamstream=Request.InputStream;
byte[]buffer=newbyte[stream.Length];
FileStreamfs=null;
try
{
   fs=newFileStream(fPath+name,FileMode.Create);
   while((stream.Read(buffer,0,buffer.Length))>0)
   {
fs.Write(buffer,0,buffer.Length);
   }
}
catch(IOExceptionioe)
{
   Response.Write(ioe);
}
finally
{
   if(fs!=null)
   {
fs.Close();
 }
   stream.Close();
}
Response.Write(name+"<br>");
Response.Write(File.Exists(fPath+name)+"<br>");
}
}
Response.Write("上传完毕"+Directory.Exists(fPath)+Path.GetFullPath(fPath));
}
}