文件上传含进度条

<%@ WebHandler Language="C#" Class="UploadHandler" %>

using System;
using System.Web;
using System.IO;
using System.Net;
using System.Data;

public class UploadHandler : IHttpHandler {

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Charset = "utf-8";
string processRandomID = string.Empty;
if (context.Request["processRandomID"] != null)
{
processRandomID = context.Request["processRandomID"].ToString().Trim();
}
HttpPostedFile oFile = context.Request.Files["Filedata"];
string strUploadPath = HttpContext.Current.Server.MapPath("/NETC/testflash") + "\\";

if (oFile != null)
{
if (!Directory.Exists(strUploadPath))
{
Directory.CreateDirectory(strUploadPath);
}
Random ro = new Random();
string stro = ro.Next(100, 100000000).ToString();//产生一个随机数用于新命名的图片
string NewName = DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + stro;
string fullfilename = string.Empty;
if (oFile.FileName.Length > 0)
{
string FileExtention = Path.GetExtension(oFile.FileName);
fullfilename = NewName + FileExtention;
oFile.SaveAs(strUploadPath + NewName + FileExtention);
//context.Response.Write(NewName + FileExtention);
}

string imgfile = HttpContext.Current.Server.MapPath("/NETC/testflash/" + fullfilename);

//异步到flash server
try
{
  string re = Upload_Request("http://xxxxxxx/flash/flashsave.aspx?filename=" + fullfilename, imgfile, fullfilename, context);
context.Response.Write(re);
}
catch (Exception ex) {}
}
else
{
context.Response.Write("0");
}
}


/// <summary>
/// 将本地文件上传到指定的服务器(HttpWebRequest方法)
/// </summary>
/// <param name="address">文件上传到的服务器</param>
/// <param name="fileNamePath">要上传的本地文件(全路径)</param>
/// <param name="fullfilename">文件名</param>
/// <param name="progressBar">上传进度条</param>
/// <returns>成功返回1,失败返回0</returns>
private string Upload_Request(string address, string fileNamePath, string fullfilename, HttpContext context)
{
string returnValue = string.Empty;

string processRandomID = string.Empty;
if (context.Request["processRandomID"] != null)
{
processRandomID = context.Request["processRandomID"].ToString().Trim();
}

// 要上传的文件
FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);

//时间戳
string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n");

//请求头部信息
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("--");
sb.Append(strBoundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append("file");
sb.Append("\"; filename=\"");
sb.Append(fullfilename);
sb.Append("\"");
sb.Append("\r\n");
sb.Append("Content-Type: ");
sb.Append("application/octet-stream");
sb.Append("\r\n");
sb.Append("\r\n");
string strPostHeader = sb.ToString();
byte[] postHeaderBytes = System.Text.Encoding.UTF8.GetBytes(strPostHeader);

// 根据uri创建HttpWebRequest对象
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(address));
httpReq.Method = "POST";

//对发送的数据不使用缓存
httpReq.AllowWriteStreamBuffering = false;

//设置获得响应的超时时间(300秒)
httpReq.Timeout = 300000;
httpReq.ContentType = "multipart/form-data; boundary=" + strBoundary;
long length = fs.Length + postHeaderBytes.Length + boundaryBytes.Length;
long fileLength = fs.Length;
httpReq.ContentLength = length;
try
{
//每次上传40k
int bufferLength = 40960;
byte[] buffer = new byte[bufferLength];

//已上传的字节数
long offset = 0;

//开始上传时间
DateTime startTime = DateTime.Now;
int size = r.Read(buffer, 0, bufferLength);
Stream postStream = httpReq.GetRequestStream();

//发送请求头部消息
postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
//context.Cache.Add(processRandomID, "0", null, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, null);
string _precentage = string.Empty;

while (size > 0)
{
postStream.Write(buffer, 0, size);
offset += size;
//progressBar.Value = (int)(offset * (int.MaxValue / length));
TimeSpan span = DateTime.Now - startTime;
double second = span.TotalSeconds;
//lblState.Text = "已上传:" + (offset * 100.0 / length).ToString("F2") + "%";
//context.Cache[processRandomID] = (offset * 100.0 / (2 * length)).ToString("F2");
_precentage = (offset * 100.0 / length).ToString("F2");

Database db = new Database();
  db.StrCon = "Data Source=xxxx;Initial Catalog=xxx;uid=xxx;pwd=xxxxxx";
DataTable dt = db.GetDataTable("select top 1 * from SF_ProcessPrecentage where PS_ProcessRandomID = '" + processRandomID + "'",CommandType.Text);
if (dt.Rows.Count > 0)
{
//update
try
{
db.ExecuteScalar("update SF_ProcessPrecentage set PS_Value = " + _precentage + ",PS_UpdateTime = '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' where PS_ProcessRandomID = '" + processRandomID + "'", CommandType.Text);
}
catch(Exception) {}

}
else
{
//insert
try
{
db.ExecuteScalar("insert into SF_ProcessPrecentage (PS_ProcessRandomID,PS_Value) values ('" + processRandomID + "'," + _precentage + ")", CommandType.Text);
}
catch(Exception) {}
}

//string tt = HttpContext.Current.Cache.Get("flash1123").ToString();
size = r.Read(buffer, 0, bufferLength);
}
//添加尾部的时间戳
postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
postStream.Close();

//获取服务器端的响应
WebResponse webRespon = httpReq.GetResponse();
Stream s = webRespon.GetResponseStream();
StreamReader sr = new StreamReader(s);

//读取服务器端返回的消息
String sReturnString = sr.ReadLine();
s.Close();
sr.Close();
returnValue = sReturnString;
//if (sReturnString.IndexOf("http://") > -1)
//{
// returnValue = 1;
//}
//else if (sReturnString == "Error")
//{
// returnValue = 0;
//}stageConnectionStrings.config

}
catch
{
returnValue = "error";
}
finally
{
fs.Close();
r.Close();
}

return returnValue;
}

public bool IsReusable {
get {
return false;
}
}

}



获取进度条文件...

public partial class uploadify_GetUploadifyProgress : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request["fileid"] != null && Request["fileid"].ToString().Trim().Length > 0)
{
try
{
//string tt = HttpContext.Current.Cache.Get(Request["fileid"].ToString()).ToString().Trim();
//Response.Write(HttpContext.Current.Cache.Get(Request["fileid"].ToString()).ToString().Trim());
Database db = new Database();
  db.StrCon = "Data Source=xxx;Initial Catalog=xxx;uid=xxx;pwd=xxxxx";
DataTable dt = db.GetDataTable("select top 1 PS_Value from SF_ProcessPrecentage where PS_ProcessRandomID = '" + Request["fileid"].ToString().Trim() + "'", CommandType.Text);
if (dt.Rows.Count > 0)
{
Response.Write(dt.Rows[0][0].ToString());
}
}
catch (Exception ex)
{
Response.Write("0");
}
Response.End();
}
else
{
Response.Write("fileid is null");
Response.End();
}
}
}


转载于:https://www.cnblogs.com/vingi/articles/2362014.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值