c#批量上傳圖片到辦事器示例分享。本站提示廣大學習愛好者:(c#批量上傳圖片到辦事器示例分享)文章只能為提供參考,不一定能成為您想要的結果。以下是c#批量上傳圖片到辦事器示例分享正文
客戶端代碼:
/// <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.WordStr("+", "%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));
}
}