基于wcf的异步上传
[OperationContract]
public void DoUpload(string fileName, byte[] context, bool append)
{
//上传目录
string folder = System.Web.Hosting.HostingEnvironment.MapPath("~/upload");
if (!System.IO.Directory.Exists(folder))
{
//如果上传目录不存在则新建一个
System.IO.Directory.CreateDirectory(folder);
}
//文件读写模式
FileMode m = FileMode.Create;
if (append)
{
//如果参数为true则表示续传,以追加模式操作文件
m = FileMode.Append;
}
//写文件操作
using (FileStream fs = new FileStream(folder + @"\" + fileName, m, FileAccess.Write))
{
fs.Write(context, 0, context.Length);
}
return;
}
void uploader_DoUploadCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
if (e.Error == null)
{
//上一个包上传成功
uploadfile file = e.UserState as uploadfile;
//修改已上传大小(显示作用)
file.sent += file.context[0].Length / 1000;
//删除已上传内容
file.context.RemoveAt(0);
//如果上传内容是空,完成操作
if (file.context.Count == 0)
{
bt.Content = "upload";
MessageBox.Show("upload OK");
}
else
{
//如果上传内容不是空,则继续剩余下一段内容上传
(sender as ServiceReference1.uploadServiceClient).DoUploadAsync(file.name, file.context[0], true, file);
//显示进度
bt.Content = file.sent.ToString() + "/" + file.size.ToString();
}
}
}
}
public class uploadfile
{
//文件名
public string name { get; set; }
//文件大小
public double size { get; set; }
//已上传
public double sent { get; set; }
//上传内容
public List<byte[]> context { get; set; }
}
//点击事件
void bt_Click(object sender, RoutedEventArgs e)
{
//选择本地文件对话框
OpenFileDialog d = new OpenFileDialog();
//文件过滤
d.Filter = "(*.*)|*.*";
//只能选单个文件
d.Multiselect = false;
//选择完成
if (d.ShowDialog() == true)
{
//文件信消
FileInfo f = d.File;
//新实例化一个文件从uploadfile类
uploadfile file = new uploadfile();
//文件名
file.name = f.Name;
//文件流内容
Stream s = f.OpenRead();
//文件大小(/1000是为了方便查看,成为k为单位)
file.size = s.Length / 1000;
//实例file的内容
file.context = new List<byte[]>();
//这里读取指定大小的文件流内容到file.context准备上传
int b;
while (s.Position > -1 && s.Position < s.Length)
{
if (s.Length - s.Position >= 300)
{
b = 3000;
}
else
{
b = (int)(s.Length - s.Position);
}
byte[] filebyte = new byte[b];
s.Read(filebyte, 0, b);
file.context.Add(filebyte);
}
s.Close();
//实例化wcf客户端
ServiceReference1.uploadServiceClient uploader = new uploadFile.ServiceReference1.uploadServiceClient();
//注册DoUpload完成事件
uploader.DoUploadCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(uploader_DoUploadCompleted);
//开始第一个包的上传
uploader.DoUploadAsync(file.name, file.context[0], false, file);
}
}