码迷,mamicode.com
首页 > Windows程序 > 详细

怎样在winform中上传图片

时间:2015-11-15 00:56:19      阅读:341      评论:0      收藏:0      [点我收藏+]

标签:

http://jingyan.baidu.com/article/b7001fe157d6b60e7382dd7f.html

因为WinForm都是运行在本地的,而我们的网站一般都是布署在服务器上,运行在服务器上的,所以在网站上面上传文件,就好似于保存文件到本地。但在WinForm上就不一样了,本章我们简单举一个在WinForm利用WebService上传文件到服务器的方法

首先们先创建一个WebService服务,该服务包含一个UpdateFile方法,该方法接收两个byte[]与string类型参数。该方法非常简单,就是按照string参数指定的路径和名称将byte[]参数值保存到服务器,代码如下:

[WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] public class WebService : System.Web.Services.WebService { [WebMethod] public bool UpdateFile(byte[] content, string pathandname) { File.WriteAllBytes(Server.MapPath(pathandname), content); } }

为了安全,我们可以验证一下pathandname的值,使其只保存图片格式的文件。全部代码如下:

[WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] public class WebService : System.Web.Services.WebService { [WebMethod] public bool UpdateFile(byte[] content, string pathandname) { int index = pathandname.LastIndexOf("."); if (index == 0) { return false; } else { string extended = string.Empty; if (index + 1 == pathandname.Length) { return false; } else { extended = pathandname.Substring(index + 1); if (extended == "jpeg" || extended == "gif" || extended == "jpg") { try { File.WriteAllBytes(Server.MapPath(pathandname), content); return true; } catch (Exception ex) { return false; } } else { return false; } } } } }

好了,创建完WebService后,将它布署到服务器上面,然后在Winform中添加对该服务的引用,添加方法如下:
在winform项目的引用-添加服务引用,在打开的对话框的地址栏中添加布署好的WebService地址,点击前往,验证通过后即添加成功了。如下图:

技术分享

然后,我们就可以在应用程序中使用它了,为了安全,我们在winform中再次验证上传文件只可以为图片。代码如下:

private void button11_Click(object sender, EventArgs e) { OpenFileDialog fileDialog = new OpenFileDialog();

if (fileDialog.ShowDialog() == DialogResult.OK) { string extension = Path.GetExtension(fileDialog.FileName); string[] str = new string[] { ".gif", ".jpge", ".jpg" }; if (!str.Contains(extension)) { MessageBox.Show("仅能上传gif,jpge,jpg格式的图片!"); } else { FileInfo fileInfo = new FileInfo(fileDialog.FileName); if (fileInfo.Length > 20480) { MessageBox.Show("上传的图片不能大于20K"); } else { Stream file = fileDialog.OpenFile();

byte[] bytes = new byte[file.Length]; file.Read(bytes, 0, bytes.Length);

//实例化WebService服务。ServiceReference1是我们在添加引用时设置的命名空间 ServiceReference1.WebServiceSoapClient WebServiceSoapClient = new AutoPage.ServiceReference1.WebServiceSoapClient();

DateTime time = DateTime.Now; //重命名图片的名称与路径 string pathandname = "/images/" + time.ToString("yyyyMMddHHmmss") + extension; if (WebServiceSoapClient.UpdateFile(bytes, pathandname)) { MessageBox.Show("上传成功!"); this.textBox1.Text = pathandname; } else { MessageBox.Show("上传失败!"); } } } } }

怎样在winform中上传图片

标签:

原文地址:http://www.cnblogs.com/qq260250932/p/4965975.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!