本文将演示如何使用Silverlight上传图片。
在Visual Studio 2008中新建一个Silverlight项目,创建时选中“Host the Silverlight application in a new Web site”复选框。
在MainPage中添加一个Button和一个TextBlock,分别用来浏览图片和显示上传后图片的名称。在Button的Click事件中添加如下代码:
private void btnUpload_Click(
object sender, RoutedEventArgs e)
...{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Multiselect = false;
dlg.Filter = "JPG 图片 (*.jpg)|*.jpg|PNG 图片 (*.png)|*.png";
bool? result = dlg.ShowDialog();
if (result != null && result == true)
{
string name = dlg.File.Name;
string extension = name.Substring(name.LastIndexOf('.'), name.Length - name.LastIndexOf('.')); //取得扩展名(包括“.”)
string uploadedName = DateTime.Now.ToString("yyyyMMddhhmmss") + extension; // 根据当前时间重命名
uploadImage(uploadedName, dlg.File.OpenRead());
uploadedImageName.Text = string.Format("上传成功!已重命名为:...{0}", uploadedName);
}
} uploadImage方法和其中用到的uploadData方法的代码如下:
private void uploadImage(
string fileName, Stream data)
...{
Uri uri = new Uri(string.Format("/DataHandler.ashx?filename={0}", fileName), UriKind.Relative);
WebClient client = new WebClient();
client.OpenWriteCompleted += delegate(object s, OpenWriteCompletedEventArgs e)
{
uploadData(data, e.Result);
e.Result.Close();
data.Close();
};
client.OpenWriteAsync(uri);
} private void uploadData(Stream input, Stream output)
...{
byte[] buffer = new byte[4096];
int bytes;
while ((bytes = input.Read(buffer, 0, buffer.Length)) != 0)
{
output.Write(buffer, 0, bytes);
}
} 在网站中添加一个Generic Handler 命名为DataHandler.ashx,后置代码如下:
public void ProcessRequest(HttpContext context)
...{
string filename = context.Request.QueryString["filename"].ToString();
public void ProcessRequest(HttpContext context)
...{
string filename = context.Request.QueryString["filename"].ToString();
using (FileStream fs = File.Create(context.Server.MapPath("~/ClientBin/Images/" + filename)))
{
SaveImage(context.Request.InputStream, fs);
}
}
private void SaveImage(Stream stream, FileStream fs)
...{
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
{
fs.Write(buffer, 0, bytesRead);
}
}
public bool IsReusable
...{
get
{
return false;
}
} 在ClientBin文件夹下面新建一个文件夹Images,到此全部工作完成,运行程序就可以上传图片了