Silverlight应用开发过程中,有时候要用到文件的上传与下载功能,以下代码为提供了相关功能的解决方法。
一、上传功能:
UpLoadDoc.ashx文件代码(服务端):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.IO;
namespace CITMPS.Web
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class UpLoadDoc : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Stream fistream = context.Request.InputStream;
try
{
string filename = DateTime.Now.Millisecond.ToString();
byte[] buffer = new byte[4096];
int byteread = 0;
using (FileStream fi = File.Create(context.Server.MapPath("ClientBin/" + context.Request.QueryString["id"].ToString()), 4096))
{
while ((byteread = fistream.Read(buffer, 0, buffer.Length)) > 0)
{
fi.Write(buffer, 0, byteread);
}
}
context.Response.ContentType = "text/plain";
context.Response.Write("Succeeded!");
}
catch (Exception e)
{
context.Response.ContentType = "text/plain";
context.Response.Write("上传失败, 错误信息:" + e.Message);
}
finally
{
fistream.Dispose();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
Silverlignt调用(客户端):
private void Button_Click_2(object sender, RoutedEventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog()
{
//Filter = "Files (*.doc,*.pdf)|.doc;.pdf",
Multiselect = false
};
if (dialog.ShowDialog() == true)
{
file = dialog.File;
long length = file.Length / 1024;
if (length <= fileMaxLength)
{
Stream stream = file.OpenRead();
txtLoadedFile.Text = file.Name;
try
{
WebClient client = new WebClient();
HtmlElement element1 = HtmlPage.Document.GetElementById("Text11");
HtmlElement element2 = HtmlPage.Document.GetElementById("Text12");
Random random = new Random();
fileCode = DateTime.Now.ToString("yyyyMMddHHmmss") + random.Next(0, 9).ToString();
string name = fileCode + file.Extension;
string url = element1.GetAttribute("value").ToString() + "?id=" + name;
fileUri = element2.GetAttribute("value").ToString() + name;
client.OpenWriteCompleted += new OpenWriteCompletedEventHandler(client_OpenWriteCompleted);
client.OpenWriteAsync(new Uri(url, UriKind.Absolute), "POST", file.OpenRead());
btnUpload.IsEnabled = false;
}
catch
{
MessageBox.Show("上传文件失败。");
}
}
else
{
MessageBox.Show("文件大小不能大于" + fileMaxLength.ToString() + "KB");
}
}
}
void client_OpenWriteCompleted(object sender, OpenWriteCompletedEventArgs e)
{
Stream inputStream = e.UserState as Stream;
Stream outputStream = e.Result;
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
outputStream.Write(buffer, 0, bytesRead);
}
outputStream.Close();
inputStream.Close();
}
二、下载功能:
DownloadFile.ashx文件代码(服务端):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
namespace CITMPS.Web
{
/// <summary>
/// Summary description for DownloadFile
/// </summary>
public class DownloadFile : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
String fileName = context.Request.QueryString["fileName"]; //客户端保存的文件名
fileName = HttpUtility.UrlDecode(fileName);
String filePath = context.Server.MapPath("ClientBin/" + 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;
}
}
}
}
Silverlignt调用(客户端):
private void btnDownload_Click(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
SignDocument doc = btn.DataContext as SignDocument;
Uri uri = new Uri(downloadFilePath + doc.Uri.Substring(doc.Uri.LastIndexOf('/') + 1), UriKind.Absolute);
HtmlPage.Window.Navigate(uri, "_self");
}