上傳大檔案-斷點續傳的一中方式的記錄

忘不掉的人發表於2018-09-26

客戶端對檔案的分割:

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(”
“);
sb.Append(“Content-Disposition: form-data; name=”” + name + “””);
sb.Append(”

“);
sb.Append(value);
sb.Append(”
“);
}
}
else
{
string[] item = poststr.Split(`=`);
if (item.Length != 2)
{
return “500”;
}
string name = item[0];
string value = item[1];
sb.Append(“–” + boundary);
sb.Append(”
“);
sb.Append(“Content-Disposition: form-data; name=”” + name + “””);
sb.Append(”

“);
sb.Append(value);
sb.Append(”
“);
}

// 檔案域的資料
sb.Append(“–” + boundary);
sb.Append(”
“);
sb.Append(“Content-Type:application/octet-stream”);
sb.Append(”
“);
sb.Append(“Content-Disposition: form-data; name=”” + fileformname + “”; filename=”” + fileName + “””);
sb.Append(”

“);

string postHeader = sb.ToString();
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);

//構造尾部資料
byte[] boundaryBytes = Encoding.UTF8.GetBytes(”
–” + boundary + “–
“);

//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();
}
}

相關文章