这篇文章主要介绍了c#批量上传图片到服务器示例,服务器端需要设置图片存储的虚拟目录,需要的朋友可以参考下
1 /// <summary>
2 /// 批量上传图片
3 /// </summary>
4 /// <param name="srcurl">服务器路径</param>
5 /// <param name="imagesPath">图片文件夹路径</param>
6 /// <param name="files">图片名称</param>
7 public void UpLoadFile(string srcurl, string imagesPath, List<string> files)
8 {
9 int count = 1;
10 foreach (string imageName in files)
11 {
12 string name = imageName;
13 string url = null;
14 //+ 加号特殊处理
15 if (name.Contains("+"))
16 {
17 url = srcurl + "name=" + name.Replace("+", "%2B");
18 }
19 else
20 {
21 url = srcurl + "name=" + name;
22 }
23 FileStream fs = new FileStream(imagesPath + name, FileMode.Open);
24 byte[] data = new byte[fs.Length];
25 fs.Read(data, 0, data.Length);
26 fs.Close();
27 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
28 request.ContentType = "image/jpeg";
29 request.Method = "POST";
30 Encoding encoding = Encoding.UTF8;
31 request.ContentLength = data.Length;
32 Stream requestStream = request.GetRequestStream();
33 requestStream.Write(data, 0, data.Length);
34 requestStream.Close();
35
36 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
37 StreamReader streamReader = new StreamReader(response.GetResponseStream(), encoding);
38 string retString = streamReader.ReadToEnd();
39 streamReader.Close();
40 Console.WriteLine((count++) + "/" + files.Count);
41 }
42 }
服务器端代码:
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using System.Web.UI;
6 using System.Web.UI.WebControls;
7 using System.Net;
8 using System.Text;
9 using System.IO;
10 public partial class upload : System.Web.UI.Page
11 {
12
13 protected void Page_Load(object sender, EventArgs e)
14 {
15 string fPath = Server.MapPath("服务器端图片存储的虚拟目录名称");//得到虚拟目录的真实路径//检查存储目录
16 if (!Directory.Exists(fPath))
17 {
18 Directory.CreateDirectory(fPath);
19 }
20 string name = Request.QueryString["name"];//得到文件名
21 HttpUtility.UrlEncode(name, Encoding.GetEncoding("UTF-8"));
22 if (name != null)
23 {
24 if (!File.Exists(fPath + name))
25 {
26 System.IO.Stream stream = Request.InputStream;
27 byte[] buffer = new byte[stream.Length];
28 FileStream fs = null;
29 try
30 {
31 fs = new FileStream(fPath + name, FileMode.Create);
32 while ((stream.Read(buffer, 0, buffer.Length)) > 0)
33 {
34 fs.Write(buffer, 0, buffer.Length);
35 }
36 }
37 catch (IOException ioe)
38 {
39 Response.Write(ioe);
40 }
41 finally
42 {
43 if (fs != null)
44 {
45 fs.Close();
46 }
47 stream.Close();
48 }
49 Response.Write(name + "<br>");
50 Response.Write(File.Exists(fPath + name) + "<br>");
51 }
52 }
53 Response.Write("上传完毕" + Directory.Exists(fPath) + Path.GetFullPath(fPath));
54 }
55 }
