客戶端對文件的分割: ind.IsBusy = true; ind.Text = "上傳中...."; string cs_str = "server=" + GlobalVars.g_ServerID + "&userid="+GlobalVars.g_userID; string url = G ...
客戶端對文件的分割:
ind.IsBusy = true;
ind.Text = "上傳中....";
string cs_str = "server=" + GlobalVars.g_ServerID + "&userid="+GlobalVars.g_userID;
string url = GlobalVars.upload_image_address + "/page/UploadProgramVedio.aspx";
ThreadPool.QueueUserWorkItem(new WaitCallback(obj =>
{
try
{
int bufferLength = 1048576;//設置每塊上傳大小為1M
byte[] buffer = new byte[bufferLength];
//已上傳的位元組數
long offset = 0;
int count = 1;//當前的塊號
int g_count = Convert.ToInt32(g_st.Length / bufferLength); //總的塊號
if (g_st.Length % bufferLength>0)
{
g_count++;
}
if (count == g_count)
{
bufferLength = Convert.ToInt32(g_st.Length);
buffer = new byte[bufferLength];
}
//開始上傳時間
int size = g_st.Read(buffer, 0, bufferLength);
while (size > 0)
{
if (close_flag)
{
return;
}
offset += size;
double pec = Math.Round(Convert.ToDouble(count*100 / g_count));
this.Dispatcher.BeginInvoke(new Action(() =>
{
ind.Text = "上傳中...." + pec + "%";
}));
//Stream st = new MemoryStream();
//st.Write(buffer, 0, bufferLength);
string ccc_str = cs_str +"&chunk=" +count+ "&chunks="+g_count;
string xx = GlobalVars.HttpUploadFile(url, ccc_str, "pic_upload", filename, buffer);
if (xx.Contains(fileExtension))
{
if (count==g_count)
{
int k = xx.IndexOf(fileExtension);
file_path = xx.Substring(0, k + fileExtension.Length);
this.Dispatcher.BeginInvoke(new Action(() =>
{
ind.IsBusy = false;
upload_flag = true;
MessageBox.Show("上傳成功!");
}));
}
}
else if (xx.Contains("200"))
{
int k = xx.IndexOf("200");
string str_count= xx.Substring(0, k + 3);
if (str_count.Contains(":"))//斷點續傳
{
string[] sstr = str_count.Split(':');
int new_chunk = 0;//斷點續傳後開始的第一塊
if (int.TryParse(sstr[0],out new_chunk))
{
new_chunk--; //保險起見防止最後一塊的問題,減一
if (count < new_chunk)
{
for (int i = count; i < new_chunk; i++)
{
count++;
size = g_st.Read(buffer, 0, bufferLength);
offset += size;
}
}
}
}
}
else
{
this.Dispatcher.BeginInvoke(new Action(() =>
{
ind.IsBusy = false;
MessageBox.Show("上傳失敗!");
}));
break;
}
//st.Close();
count++;
if (count == g_count)
{
bufferLength = Convert.ToInt32(g_st.Length - offset);
buffer = new byte[bufferLength];
size = g_st.Read(buffer, 0, bufferLength);
}
else
{
size = g_st.Read(buffer, 0, bufferLength);
}
}
g_st.Close();
}
catch (Exception ex)
{
this.Dispatcher.BeginInvoke(new Action(() =>
{
ind.IsBusy = false;
MessageBox.Show("上傳失敗!" + ex.ToString());
}));
}
finally
{
//imgFileBytes = null;
g_st.Close();
g_st = null;
}
}));
http 上傳文件的方法:
/// <summary>
/// http上傳文件
/// </summary>
/// <param name="url">url地址</param>
/// <param name="poststr">參數 user=eking&pass=123456</param>
/// <param name="fileformname">文件對應的參數名</param>
/// <param name="fileName">文件名字</param>
/// <param name="bt">文件流</param>
/// <returns></returns>
public static string HttpUploadFile(string url, string poststr, string fileformname, string fileName, byte[] bt,Stream stream = null )
{
try
{
// 這個可以是改變的,也可以是下麵這個固定的字元串
string boundary = "ceshi";
// 創建request對象
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
webrequest.ContentType = "multipart/form-data;boundary=" + boundary;
webrequest.Method = "POST";
// 構造發送數據
StringBuilder sb = new StringBuilder();
// 文本域的數據,將user=eking&pass=123456 格式的文本域拆分 ,然後構造
if (poststr.Contains("&"))
{
foreach (string c in poststr.Split('&'))
{
string[] item = c.Split('=');
if (item.Length != 2)
{
break;
}
string name = item[0];
string value = item[1];
sb.Append("--" + boundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"" + name + "\"");
sb.Append("\r\n\r\n");
sb.Append(value);
sb.Append("\r\n");
}
}
else
{
string[] item = poststr.Split('=');
if (item.Length != 2)
{
return "500";
}
string name = item[0];
string value = item[1];
sb.Append("--" + boundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"" + name + "\"");
sb.Append("\r\n\r\n");
sb.Append(value);
sb.Append("\r\n");
}
// 文件域的數據
sb.Append("--" + boundary);
sb.Append("\r\n");
sb.Append("Content-Type:application/octet-stream");
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"" + fileformname + "\"; filename=\"" + fileName + "\"");
sb.Append("\r\n\r\n");
string postHeader = sb.ToString();
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);
//構造尾部數據
byte[] boundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
//string filePath = @"C:/2.html";
//string fileName = "2.html";
//byte[] fileContentByte = new byte[1024]; // 文件內容二進位
if (bt != null && stream == null)
{
long length = postHeaderBytes.Length + bt.Length + boundaryBytes.Length;
webrequest.ContentLength = length;
}
else if (bt == null && stream != null)
{
long length = postHeaderBytes.Length + stream.Length + boundaryBytes.Length;
webrequest.ContentLength = length;
}
Stream requestStream = webrequest.GetRequestStream();
// 輸入頭部數據 要按順序
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
// 輸入文件流數據
if (bt != null && stream == null)
{
requestStream.Write(bt, 0, bt.Length);
}
else if (bt == null && stream != null)
{
stream.CopyTo(requestStream);
}
// 輸入尾部數據
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
WebResponse responce = webrequest.GetResponse();
Stream s = responce.GetResponseStream();
StreamReader sr = new StreamReader(s);
// 返回數據流(源碼)
return sr.ReadToEnd();
}
catch (Exception ex)
{
GlobalFunc.LogError("HttpUploadFile錯誤:" + ex.Message + ex.StackTrace);
return "500";
}
finally
{
if (stream!=null)
{
stream.Close();
}
}
}
服務端方法:
protected void doUpload()
{
int rand_flag = 0;//0為隨機名 1為預設值
string imageRoot = "";
if (ConfigurationManager.ConnectionStrings["upload_image_path"] != null)
{
imageRoot = ConfigurationManager.ConnectionStrings["upload_image_path"].ConnectionString;
if (imageRoot.EndsWith("/"))
{
imageRoot = imageRoot.Substring(0, imageRoot.Length - 1);
}
}
if (imageRoot == null || imageRoot == "")
{
Response.Write("<script language='javascript'>alert('請配置視頻目錄!'); window.location.reload();</script>");
Response.End();
}
server_id = Request["server"];
user_id = Request["userid"];
int chunk = Convert.ToInt32(Request["chunk"]); //當前分塊
int chunks = Convert.ToInt32(Request["chunks"]);//總的分塊數量
if (!int.TryParse(Request["rand_flag"],out rand_flag))
{
}
if (Request.Files["pic_upload"].ContentLength > 0)//驗證是否包含文件
{
string fileName = Request.Files["pic_upload"].FileName;
string newFileName = fileName;
if (chunks > 1)
{
newFileName = chunk + "_" + fileName; //按文件塊重命名塊文件
}
//取得文件的擴展名,並轉換成小寫
string fileExtension = Path.GetExtension(Request.Files["pic_upload"].FileName).ToLower();
//fileName += fileExtension;//完整文件名
//圖片目錄規則: 網站根目錄 +serverid(目錄名)+images(目錄名)+ userid(目錄名)+圖片文件名
string virtul_filepath = "/vedio/" + server_id + "/" + user_id+"/";//相對路徑
string filepath = imageRoot + virtul_filepath;//絕對路徑
if (Directory.Exists(filepath) == false)//如果不存在就創建file文件夾,及其縮略圖文件夾
{
try
{
Directory.CreateDirectory(filepath);
}
catch (Exception ex)
{
Response.Write("<script language='javascript'>alert('生成路徑出錯!" + ex.Message + "'); window.location.reload();</script>");
Response.End();
}
}
string virtual_allfileName = virtul_filepath + newFileName;// 包含相對路徑的文件名
string allfileName = filepath + newFileName;// 包含絕對路徑的文件名
if (chunks > 1&& System.IO.File.Exists(allfileName))
{
for (int i = 1; i < chunks; i++)
{
//檢測已存在磁碟的文件區塊
if (!System.IO.File.Exists(filepath + i.ToString() + "_" + fileName))
{
Response.Write(i+":200");
return;
}
}
}
string name = "";
Random rd = new Random();
name = DateTime.Now.ToString("yyyyMMddHHmmss") + rd.Next(1000, 9999)+ fileExtension;
if (chunks == 1)
{
if (rand_flag == 1)
{
allfileName = filepath + fileName;
virtual_allfileName = virtul_filepath + fileName;
}
else
{
allfileName = filepath + name;
virtual_allfileName = virtul_filepath + name;
}
}
Request.Files["pic_upload"].SaveAs(allfileName);//保存文件
//將保存的路徑,圖片備註等信息插入資料庫
try
{
if (chunks == 1)
{
Response.Write(virtual_allfileName);
}
else if (chunks > 1 && chunk == chunks) //判斷塊總數大於1 並且當前分塊==塊總數(指示是否為最後一個分塊)
{
if (rand_flag==1)
{
using (FileStream fsw = new FileStream(filepath + fileName, FileMode.Create, FileAccess.ReadWrite))
{
// 遍歷文件合併
for (int i = 1; i <= chunks; i++)
{
var data = System.IO.File.ReadAllBytes(filepath + i.ToString() + "_" + fileName);
fsw.Write(data, 0, data.Length);
System.IO.File.Delete(filepath + i.ToString() + "_" + fileName); //刪除指定文件信息
}
fsw.Position = 0;
Response.Write(virtul_filepath + fileName);
}
}
else
{
using (FileStream fsw = new FileStream(filepath + name, FileMode.Create, FileAccess.ReadWrite))
{
// 遍歷文件合併
for (int i = 1; i <= chunks; i++)
{
var data = System.IO.File.ReadAllBytes(filepath + i.ToString() + "_" + fileName);
fsw.Write(data, 0, data.Length);
System.IO.File.Delete(filepath + i.ToString() + "_" + fileName); //刪除指定文件信息
}
fsw.Position = 0;
Response.Write(virtul_filepath + name);
}
}
}
else
{
Response.Write("200");
}
}
catch (Exception ex)
{
Response.Write("<script language='javascript'>alert('上傳出錯!" + ex.Message + "'); window.location.reload();</script>");
Response.End();
}
}
else
{
Response.Write("<script language='javascript'>alert('請選擇要上傳的文件!'); window.location.reload();</script>");
Response.End();
}
}