Silverlight实现文件的上传与下载
(1)实现上传附件
silverlight端代码:
private void button1_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
if (dialog.ShowDialog().Value)
{
// 选择上传的文件
FileInfo file = dialog.File;
Stream stream = file.OpenRead();
stream.Position = 0;
byte[] buffer = new byte[stream.Length + 1];
//将文件读入字节数组
stream.Read(buffer, 0, buffer.Length);
String fileExtention = file.Extension;
//调用服务上传
ServiceReference1.UploadFileSoapClient upfile = new UploadFileSoapClient();
upfile.UploadfileAsync(buffer, fileExtention);
upfile.UploadfileCompleted += new EventHandler<UploadfileCompletedEventArgs>(upfile_UploadfileCompleted);
}
else
{
MessageBox.Show("请选择文件!");
}
}
void upfile_UploadfileCompleted(object sender, UploadfileCompletedEventArgs e)
{
MessageBox.Show("上传成功!");
}
{
OpenFileDialog dialog = new OpenFileDialog();
if (dialog.ShowDialog().Value)
{
// 选择上传的文件
FileInfo file = dialog.File;
Stream stream = file.OpenRead();
stream.Position = 0;
byte[] buffer = new byte[stream.Length + 1];
//将文件读入字节数组
stream.Read(buffer, 0, buffer.Length);
String fileExtention = file.Extension;
//调用服务上传
ServiceReference1.UploadFileSoapClient upfile = new UploadFileSoapClient();
upfile.UploadfileAsync(buffer, fileExtention);
upfile.UploadfileCompleted += new EventHandler<UploadfileCompletedEventArgs>(upfile_UploadfileCompleted);
}
else
{
MessageBox.Show("请选择文件!");
}
}
void upfile_UploadfileCompleted(object sender, UploadfileCompletedEventArgs e)
{
MessageBox.Show("上传成功!");
}
webservice代码:
[WebMethod]
public int Uploadfile(byte[] FileByte, string FileExtention)
{
//文件存放路径
string filepath = string.Format(@"D:\example{0}", FileExtention);
//如果文件已经存在则删除
if (File.Exists(filepath))
File.Delete(filepath);
//创建文件流实例,用于写入文件
FileStream stream = new FileStream(filepath, FileMode.CreateNew);
//写入文件
stream.Write(FileByte, 0, FileByte.Length);
stream.Close();
return FileByte.Length;
}
public int Uploadfile(byte[] FileByte, string FileExtention)
{
//文件存放路径
string filepath = string.Format(@"D:\example{0}", FileExtention);
//如果文件已经存在则删除
if (File.Exists(filepath))
File.Delete(filepath);
//创建文件流实例,用于写入文件
FileStream stream = new FileStream(filepath, FileMode.CreateNew);
//写入文件
stream.Write(FileByte, 0, FileByte.Length);
stream.Close();
return FileByte.Length;
}
(2)
public void UploadFile(EBillType eBillType,int nBillID, byte[] arrFileByte, string sFileName, string sFileType, string sRemarks)
{
FileStream objFileStream = null;
try
{
// 以时间命名文件夹
sFileName = sFileName.Substring(0, sFileName.LastIndexOf(".") - 1) + (DateTime.Now.ToString("yyyyMMddhhssmm"));
//文件存放路径
string sFilePath = string.Format(@"D:\MyWork\MRP系统\MRP\MRPService\MRPService\Files\{0}{1}", sFileName, sFileType);
//String fileExtention = file.Extension;
//sFileType = sFileType.Substring(sFileType.LastIndexOf(".") + 1).ToLower();
//调用服务上传支持的文件格式
if (sFileType != ".xls" && sFileType != ".doc" && sFileType !=".pdf")
{
throw new Exception("上传文件格式不支持!");
}
//如果文件已经存在则删除
if (File.Exists(sFilePath))
File.Delete(sFilePath);
//创建文件流实例,用于写入文件
//string sWebConfig = System.Configuration.ConfigurationSettings.AppSettings["AttachDbFilename"];
//string sWebConfig = "D:\MyWork\MRP系统\MRP\MRPService\MRPService";
objFileStream = new FileStream( sFilePath, FileMode.CreateNew);
//写入文件
objFileStream.Write(arrFileByte, 0, arrFileByte.Length);
objFileStream.Close();
//保存到数据库
CUploadFile objUploadFile = new CUploadFile(eBillType, nBillID, base.LogUserID, base.LogUserName, base.LogUserCode, base.LogDeptID, base.LogDeptName);
objUploadFile.FileName = sFileName;
objUploadFile.FilePath = sFilePath;
objUploadFile.FileSize = arrFileByte.Length;
objUploadFile.FileType = sFileType;
UploadFileDAL.Save(objUploadFile);
}
catch (Exception ex)
{
throw ex;
}
finally
{
objFileStream = null;
}
} 下载文件:
{
FileStream objFileStream = null;
try
{
// 以时间命名文件夹
sFileName = sFileName.Substring(0, sFileName.LastIndexOf(".") - 1) + (DateTime.Now.ToString("yyyyMMddhhssmm"));
//文件存放路径
string sFilePath = string.Format(@"D:\MyWork\MRP系统\MRP\MRPService\MRPService\Files\{0}{1}", sFileName, sFileType);
//String fileExtention = file.Extension;
//sFileType = sFileType.Substring(sFileType.LastIndexOf(".") + 1).ToLower();
//调用服务上传支持的文件格式
if (sFileType != ".xls" && sFileType != ".doc" && sFileType !=".pdf")
{
throw new Exception("上传文件格式不支持!");
}
//如果文件已经存在则删除
if (File.Exists(sFilePath))
File.Delete(sFilePath);
//创建文件流实例,用于写入文件
//string sWebConfig = System.Configuration.ConfigurationSettings.AppSettings["AttachDbFilename"];
//string sWebConfig = "D:\MyWork\MRP系统\MRP\MRPService\MRPService";
objFileStream = new FileStream( sFilePath, FileMode.CreateNew);
//写入文件
objFileStream.Write(arrFileByte, 0, arrFileByte.Length);
objFileStream.Close();
//保存到数据库
CUploadFile objUploadFile = new CUploadFile(eBillType, nBillID, base.LogUserID, base.LogUserName, base.LogUserCode, base.LogDeptID, base.LogDeptName);
objUploadFile.FileName = sFileName;
objUploadFile.FilePath = sFilePath;
objUploadFile.FileSize = arrFileByte.Length;
objUploadFile.FileType = sFileType;
UploadFileDAL.Save(objUploadFile);
}
catch (Exception ex)
{
throw ex;
}
finally
{
objFileStream = null;
}
} 下载文件:
public void ProcessRequest(HttpContext context)
{
String fileName = context.Request.QueryString["fileName"]; //客户端保存的文件名
fileName=HttpUtility.UrlDecode(fileName);
String filePath = context.Server.MapPath("data/" + fileName); //路径
FileInfo fileInfo = new FileInfo(filePath);
if (fileInfo.Exists)
{
byte[] buffer = new byte[102400];
context.Response.Clear();
FileStream iStream = File.OpenRead(filePath);
long dataLengthToRead = iStream.Length; //获取下载的文件总大小
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" +
HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
while (dataLengthToRead > 0 && context.Response.IsClientConnected)
{
int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(102400));//'读取的大小
context.Response.OutputStream.Write(buffer, 0, lengthRead);
context.Response.Flush();
dataLengthToRead = dataLengthToRead - lengthRead;
}
context.Response.Close();
context.Response.End();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
{
String fileName = context.Request.QueryString["fileName"]; //客户端保存的文件名
fileName=HttpUtility.UrlDecode(fileName);
String filePath = context.Server.MapPath("data/" + fileName); //路径
FileInfo fileInfo = new FileInfo(filePath);
if (fileInfo.Exists)
{
byte[] buffer = new byte[102400];
context.Response.Clear();
FileStream iStream = File.OpenRead(filePath);
long dataLengthToRead = iStream.Length; //获取下载的文件总大小
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" +
HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
while (dataLengthToRead > 0 && context.Response.IsClientConnected)
{
int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(102400));//'读取的大小
context.Response.OutputStream.Write(buffer, 0, lengthRead);
context.Response.Flush();
dataLengthToRead = dataLengthToRead - lengthRead;
}
context.Response.Close();
context.Response.End();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
当我们新建玩这个类的时候,就可以在你点击下载的按钮那里写事件来调用这个类进行下载文件!但是条件是你的文件是存在固定的一个文件夹中的.只有找到路径才可以下载的。
private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
{
string fileaddressofneeded = “1.txt”;//需要下载的文件名字
HyperlinkButton hlbutton = sender as HyperlinkButton;
var client = new WebClient();
var u= new Uri(String.Format("{0}/http://www.cnblogs.com/Handler/DownLoadFileHandler.ashx?FileName={1}" ,client.BaseAddress, fileaddressofneeded),UriKind.RelativeOrAbsolute);
hlbutton.NavigateUri = u;
}
{
string fileaddressofneeded = “1.txt”;//需要下载的文件名字
HyperlinkButton hlbutton = sender as HyperlinkButton;
var client = new WebClient();
var u= new Uri(String.Format("{0}/http://www.cnblogs.com/Handler/DownLoadFileHandler.ashx?FileName={1}" ,client.BaseAddress, fileaddressofneeded),UriKind.RelativeOrAbsolute);
hlbutton.NavigateUri = u;
}
本文来自dingke627的博客,原文地址:http://blog.csdn.net/dingke627/article/details/6947602