silverlight upload(转)
silverlight上传文件
silverlight不支持本地文件创建等相关操作,上传文件时可以先把文件读入字节数组,然后调用web服务实现上传。
具体实现如下:
silverlight端代码:
private void button1_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
if (dialog.ShowDialog().Value)
{
// 选择上传的文件
FileInfo file = dialog.File;
var fileName = dialog.File;
string strName = fileName.ToString();
Stream stream = file.OpenRead();
stream.Position = 0;
byte[] buffer = new byte[stream.Length + 1];
//将文件读入字节数组
stream.Read(buffer, 0, buffer.Length);
String fileExtention = file.Extension;
//调用服务上传
WebService1SoapClient upfile = new WebService1SoapClient();
// ServiceReference1.UploadFileSoapClient upfile = new UploadFileSoapClient();
upfile.UploadfileCompleted += new EventHandler<UploadfileCompletedEventArgs>(upfile_UploadfileCompleted);
upfile.UploadfileAsync(buffer, strName, fileExtention);
}
else
{
MessageBox.Show("请选择文件!");
}
}
void upfile_UploadfileCompleted(object sender, UploadfileCompletedEventArgs e)
{
MessageBox.Show("上传成功!");
}
webservice代码:
[WebMethod]
public int Uploadfile(byte[] FileByte,string FileName, string FileExtention)
{
//文件存放路径
//string filepath = string.Format(@"D:\" + FileName + "{0}", FileExtention);
string str = Server.MapPath("~/");
str = str.Substring(0, str.Length - 5)+"\\";
string FilePath = str + "Image";
string filepath = string.Format(FilePath + "\\" + FileName + "{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;
}
WebService
[WebMethod]
public byte[] Readfile(string FileName, string FileExtention)
{
string str = Server.MapPath("~/");
str = str.Substring(0, str.Length - 5)+"\\";
string FilePath = str + "Image";
//FileName = FileName.Substring(0, FileName.Length - 4);
string strfile=string.Format(FilePath + "\\" + FileName + "{0}", FileExtention);
if (File.Exists(strfile))
File.ReadAllBytes(strfile);
try
{
Stream stream = new FileStream(strfile, FileMode.Open);
byte[] FileByte = new byte[stream.Length];
// 读出文件
stream.Read(FileByte, 0, FileByte.Length);
stream.Close();
return FileByte;
}
catch (Exception ex)
{
return null;
}
}
Cs
WebService1SoapClient upfile;
string strName;
byte[] buffer;
String fileExtention;
private void button3_Click(object sender, RoutedEventArgs e)
{
strName = textBox1.Text;
fileExtention = "";
upfile.ReadfileCompleted += new EventHandler<ReadfileCompletedEventArgs>(upfile_ReadfileCompleted);
upfile.ReadfileAsync(strName, fileExtention);
}
void upfile_ReadfileCompleted(object sender, ReadfileCompletedEventArgs e)
{
buffer = e.Result;
Stream image = new MemoryStream(buffer);
BitmapImage bi = new BitmapImage();
bi.SetSource(image);
image1.Source = bi;
}
}