通过WebService上传任何类型的文件
1.简介
本文描述了一种方法,通过Web服务从Windows窗体应用程序,可用于所有类型的文件上传。证明的方法不依赖于ASP.NET文件上传控件,并允许开发人员有机会上传文件的编程,而无需用户干预。这种做法可能是有用的,做这样的事情处理本地消息队列中的内容时,互联网服务是可用的(如果用户群是移动,只有间歇性的连接)。文章还讨论了为先导,以允许文件上传,通过服务使用的文件大小检查。
2.服务器端WebService编写
首先在VS中创建一个Webservice工程,并在WebService中编写如下方法:
- [WebMethod]
- public string UploadFile(byte[] f, string fileName)
- {
- try
- {
- MemoryStream ms = new MemoryStream(f);
- FileStream fs = new FileStream
- (System.Web.Hosting.HostingEnvironment.MapPath
- ("~/TransientStorage/") +
- fileName, FileMode.Create);
- ms.WriteTo(fs);
- ms.Close();
- fs.Close();
- fs.Dispose();
- return "OK";
- }
- catch (Exception ex)
- {
- return ex.Message.ToString();
- }
- }
3.客户端窗体程序编写
客户端上传文件的方法编写如下:
- private void UploadFile(string filename)
- {
- try
- {
- String strFile = System.IO.Path.GetFileName(filename);
- TestUploader.Uploader.FileUploader srv = new
- TestUploader.Uploader.FileUploader();
- FileInfo fInfo = new FileInfo(filename);
- long numBytes = fInfo.Length;
- double dLen = Convert.ToDouble(fInfo.Length / 1000000);
- if (dLen < 4) // 文件上传有4M限制,超过4M的需要分割发送
- {
- FileStream fStream = new FileStream(filename,
- FileMode.Open, FileAccess.Read);
- BinaryReader br = new BinaryReader(fStream);
- byte[] data = br.ReadBytes((int)numBytes);
- br.Close();
- service
- string sTmp = srv.UploadFile(data, strFile);
- fStream.Close();
- fStream.Dispose();
- message
- MessageBox.Show("File Upload Status: " + sTmp, "File
- Upload");
- }
- else
- {
- MessageBox.Show("The file selected exceeds the size limit
- for uploads.", "File Size");
- }
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.Message.ToString(), "Upload Error");
- }
- }
4.客户端文件上传示例
新建一个窗体工程,并在窗体上拖放两个Button,一个TextBox控件,一个按钮是浏览文件,一个按钮上传文件,TextBox显示文件路径。
1)浏览文件代码
- private void btnBrowse_Click(object sender, EventArgs e)
- {
- openFileDialog1.Title = "打开文件";
- openFileDialog1.Filter = "所有文件|*.*";
- openFileDialog1.FileName = "";
- try
- {
- openFileDialog1.InitialDirectory = "C:\\Temp";
- }
- catch{ }
- openFileDialog1.ShowDialog();
- if (openFileDialog1.FileName == "")
- return;
- else
- txtFileName.Text = openFileDialog1.FileName;
- }
2)文件上传的代码
- private void btnUpload_Click(object sender, EventArgs e)
- {
- if (txtFileName.Text != string.Empty)
- UploadFile(txtFileName.Text);
- else
- MessageBox.Show("请选择要上传的文件!", "没有选择文件");
- }