Client
---------------------
public delegate void GenHandler<T>(T obj);
public partial class frmFileUpload : Form
{
string filePath = string.Empty;
public frmFileUpload()
{
InitializeComponent();
}
private void btnUploadFileToWebService_Click(object sender, EventArgs e)
{
OpenFileDialog dg = new OpenFileDialog();
dg.Multiselect = false;
if (dg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
filePath = dg.FileName;
WebClient client = new WebClient();
client.Credentials = CredentialCache.DefaultCredentials;
client.OpenWriteCompleted += client_OpenWriteCompleted;
UriBuilder ub = new UriBuilder("http://...ashx");
ub.Query = string.Format("fileName={0}", new FileInfo(filePath).Name);
client.OpenWriteAsync(ub.Uri);
}
}
void client_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
{
if (File.Exists(filePath))
{
System.IO.BinaryReader r = new System.IO.BinaryReader(File.OpenRead(filePath));
while (r.BaseStream.Position < r.BaseStream.Length - 1)
{
byte[] bts = r.ReadBytes(10);
if (bts.Length > 0)
{
e.Result.Write(bts, 0, bts.Length);
int per = (int)(((r.BaseStream.Position + 1) * 100) / r.BaseStream.Length);
string strPer = string.Format("{0}%", per);
OutPutProgress(strPer);
}
}
e.Result.Close();
r.Close();
}
}
private void OutPutProgress(string progress)
{
if (this.InvokeRequired)
{
this.Invoke(new GenHandler<string>(OutPutProgress), progress);
}
else
{
this.Text = progress;
}
}
}
Service
---------------------
/// <summary>
/// 文档数据存储服务
/// </summary>
public class DocReceiver : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("文档数据存储服务。\r\n");
try
{
context.Response.Write("数据接收开始...\r\n");
string id = context.Request.Form["docId"];
string fileName = context.Request.QueryString["fileName"];
if (string.IsNullOrEmpty(fileName))
{
fileName = DateTime.Now.ToString("yyMMddHHmmss_") + Guid.NewGuid().ToString() + ".xls";
}
else
{
fileName = DateTime.Now.ToString("yyMMddHHmmss_") + fileName;
}
string path = context.Server.MapPath("~/[upload]/" + fileName);
Stream inStream = context.Request.InputStream;
if (inStream != null && inStream.Length > 0)
{
FileInfo fi = new FileInfo(path);
if (!fi.Directory.Exists)
{
fi.Directory.Create();
}
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
{
int count;
byte[] buffer = new byte[1024];
while ((count = inStream.Read(buffer, 0, 1024)) > 0)
{
fs.Write(buffer, 0, count);
}
}
}
context.Response.Write("数据接收完毕。\r\n");
}
catch (Exception ex)
{
context.Response.Write("数据接收失败。\r\n");
context.Response.Write(ex.Message + "\r\n");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}