WebService思路及功能实现
实现思路:通过添加Web服务来实现
上传功能实现
一.获得本地文件并转化为字节数组传入到服务端
private void buttonUpload_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
System.IO.Stream uploadStream = null;
openFileDialog.Filter = "Jpeg Files (*.jpg)|*.jpg|All Files(*.*)|*.*";
openFileDialog.Multiselect = false;
if (openFileDialog.ShowDialog()==true)
{
fileinfo = openFileDialog.File;
uploadStream = fileinfo.OpenRead();
byte[] buffer = new byte[uploadStream.Length];
//将选择的文件信息流写入到字节数组中
uploadStream.Read(buffer, 0, buffer.Length);
if (fileinfo!=null)
{
c.ActionUploadCompleted += new EventHandler<AsyncCompletedEventArgs>(c_ActionUploadCompleted);
c.ActionUploadAsync(fileinfo.Name, buffer, true);
}
}
}
二.服务端捕获字节数组并还原文件
/// <summary>
/// 上传功能
/// </summary>
/// <param name="fileName">文件名</param>
/// <param name="fileData">字节流</param>
/// <param name="isApplend">是否追加</param>
[WebMethod]
public void ActionUpload(string fileName, byte[] fileData, bool isApplend)
{
if (!Directory.Exists(uploadFolder))
{
Directory.CreateDirectory(uploadFolder);
}
FileMode fileMode = isApplend ? FileMode.Append : FileMode.Create;
using(FileStream fs=new FileStream(uploadFolder+@"\"+fileName,fileMode,FileAccess.Write))
{
fs.Write(fileData,0,fileData.Length);
}
}
下载功能实现
一.客户端传入下载文件名,服务端捕获文件名并传回该文件的字节数组
客户端代码:
private void buttonBase_Click(object sender, RoutedEventArgs e)
{
UploadFileWebServiceSoapClient c2 = new UploadFileWebServiceSoapClient();
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.Filter = "Jpeg Files (*.jpg)|*.jpg|All Files(*.*)|*.*";
//给下载文件一个默认的Name
saveDialog.DefaultFileName = "yl";
if (listBox1.SelectedItems.Count < 0)
{
MessageBox.Show("请选择要下载的下载文件");
}
else if (listBox1.SelectedItems.Count > 1)
{
MessageBox.Show("暂不提供批量下载");
}
else
{
if (saveDialog.ShowDialog()==true)
{
c2.getBinaryFileCompleted += new EventHandler<getBinaryFileCompletedEventArgs>(c2_getBinaryFileCompleted);
c2.getBinaryFileAsync(listBox1.SelectedItem.ToString(),saveDialog);
}
}
}
服务端代码:
/// <summary>
/// 返回下载文件的字节流,直接返回一个Stream流怎么老是返回不了呢。悲哀
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
[WebMethod]
public byte[] getBinaryFile(string filename)
{
string downloadsorcepath = uploadFolder + @"\" + filename;
if (File.Exists(downloadsorcepath))
{
try
{
FileStream s2 = File.OpenRead(downloadsorcepath);
byte[] downloadbyte = new byte[s2.Length];
s2.Read(downloadbyte, 0, downloadbyte.Length);
s2.Close();
return downloadbyte;
}
catch (Exception)
{
return new byte[0];
}
}
else
{
return new byte[0];
}
}
二.客户端捕获服务端传回的字节数组,并还原文件保存在本地
void c2_getBinaryFileCompleted(object sender, getBinaryFileCompletedEventArgs e)
{
if (e.Error==null)
{
byte[] mybyte = new byte[e.Result.Length];
mybyte = e.Result;
SaveFileDialog saveDialog = (SaveFileDialog)e.UserState;
using (Stream stream =saveDialog.OpenFile())
{
stream.Write(mybyte, 0, mybyte.Length);
}
}
}