首页 > Python基础教程 >
-
C#教程之上传大文件-断点续传的一中方式的记录
客户端对文件的分割:
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();
}
}