怎样在winform中上传图片
1、首先们先创建一个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;
}
}
}
}
}
2、好了,创建完WebService后,将它布署到服务器上面,然后在Winform中添加对该服务的引用芬改,添加方法如下:
在winform项目的引用-添加服务引用,在打光截袭开的对话框的地址栏中添加布署好的WebService地址,点击前往,验证通过后即添加成功了。如下图:

3、然后,我们就可以在应用程序中使用它了,为了安全,我们在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("上传失败!");
}
}
}
}
}
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
阅读量:22
阅读量:39
阅读量:88
阅读量:89
阅读量:39