手机
当前位置:查字典教程网 >编程开发 >C#教程 >c#批量上传图片到服务器示例分享
c#批量上传图片到服务器示例分享
摘要:客户端代码:复制代码代码如下://////批量上传图片//////服务器路径///图片文件夹路径///图片名称publicvoidUpLoa...

客户端代码:

复制代码 代码如下:

/// <summary>

/// 批量上传图片

/// </summary>

/// <param name="srcurl">服务器路径</param>

/// <param name="imagesPath">图片文件夹路径</param>

/// <param name="files">图片名称</param>

public void UpLoadFile(string srcurl, string imagesPath, List<string> files)

{

int count = 1;

foreach (string imageName in files)

{

string name = imageName;

string url = null;

//+ 加号特殊处理

if (name.Contains("+"))

{

url = srcurl + "name=" + name.Replace("+", "%2B");

}

else

{

url = srcurl + "name=" + name;

}

FileStream fs = new FileStream(imagesPath + name, FileMode.Open);

byte[] data = new byte[fs.Length];

fs.Read(data, 0, data.Length);

fs.Close();

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

request.ContentType = "image/jpeg";

request.Method = "POST";

Encoding encoding = Encoding.UTF8;

request.ContentLength = data.Length;

Stream requestStream = request.GetRequestStream();

requestStream.Write(data, 0, data.Length);

requestStream.Close();

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

StreamReader streamReader = new StreamReader(response.GetResponseStream(), encoding);

string retString = streamReader.ReadToEnd();

streamReader.Close();

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

}

}

服务器端代码:

复制代码 代码如下:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Net;

using System.Text;

using System.IO;

public partial class upload : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

string fPath = Server.MapPath("服务器端图片存储的虚拟目录名称");//得到虚拟目录的真实路径//检查存储目录

if (!Directory.Exists(fPath))

{

Directory.CreateDirectory(fPath);

}

string name = Request.QueryString["name"];//得到文件名

HttpUtility.UrlEncode(name, Encoding.GetEncoding("UTF-8"));

if (name != null)

{

if (!File.Exists(fPath + name))

{

System.IO.Stream stream = Request.InputStream;

byte[] buffer = new byte[stream.Length];

FileStream fs = null;

try

{

fs = new FileStream(fPath + name, FileMode.Create);

while ((stream.Read(buffer, 0, buffer.Length)) > 0)

{

fs.Write(buffer, 0, buffer.Length);

}

}

catch (IOException ioe)

{

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));

}

}

【c#批量上传图片到服务器示例分享】相关文章:

读取图片像素的具体实例

c# 开机启动项的小例子

c# dataTable 合并两个列到一个新列中的简单实例

C#编写Windows服务实例代码

c#高效比对大量图片的实例代码

c# 生成随机时间的小例子

c#给图片添加文字的代码小结

C#编写的windows计算器的实例代码

c# 服务器上传木马监控代码(包含可疑文件)

如何随机选取一个机器的ip

精品推荐
分类导航