今天朋友叫我给他写个winform可以选择多个文件,上传到web iis服务器,然后可以指定保存到服务器的某个目录,并返回保存的路径,然后上传的时候显示上传进度,上传速度等。。。
由于一直再用webapi,好久没写webservice服务,导致有点生疏,用了一下午才写出来,最近也在玩博客了,所以特开一篇记录
winform静态调用webservice
步骤 创建webservice服务
生成一个HelloWorld接口
此时在winform客户端
动态调用
post
string strURL = "http://localhost:62680/Demo.asmx/HelloWorld";
//创建一个HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
//Post请求方式
request.Method = "POST";
//内容类型
request.ContentType = "application/x-www-form-urlencoded";
//发送请求,获得请求流
Stream writer = request.GetRequestStream();
//关闭请求流
writer.Close();
//获得响应流
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream s = response.GetResponseStream();
//转化为XML,自己进行处理
XmlTextReader Reader = new XmlTextReader(s);
Reader.MoveToContent();
string strValue = Reader.ReadInnerXml();
MessageBox.Show(strValue);
Reader.Close();
get
string strURL = "http://localhost:62680/Demo.asmx/HelloWorld? s = ";
strURL += "this.textBox1.Text";
//创建一个HTTP请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
request.Method="get";
HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
Stream s = response.GetResponseStream();
//转化为XML,自己进行处理
XmlTextReader Reader = new XmlTextReader(s);
Reader.MoveToContent();
string strValue = Reader.ReadInnerXml();
MessageBox.Show(strValue);
Reader.Close();
扩展winform可以选择多个文件,上传到web iis服务器
服务端代码
[WebMethod]
public string Upload_File()
{
try
{
HttpFileCollection file_list = HttpContext.Current.Request.Files;
if (file_list != null && file_list.Count > 0)
{
string str = string.Empty;
for (int i = 0; i < file_list.Count; i++)
{
HttpPostedFile file = file_list[i];
string type = file.ContentType;//获取文件类型
bool blnReplace = file.FileName.EndsWith("$1");
string _FileName = file.FileName;
if (blnReplace)
_FileName = _FileName.Substring(0, _FileName.Length - 2);
else
{
if (File.Exists(HttpContext.Current.Server.MapPath("~/" + _FileName)))
{
return "文件已存在";
}
}
string FileName = Path.GetFileName(_FileName);
string dir = Path.GetDirectoryName(_FileName);
if (FileName != null && FileName != "")
{
//定义文件存放的目标路径
string targetDir = HttpContext.Current.Server.MapPath("~/" + dir);
if (!Directory.Exists(targetDir))
//创建目标路径
Directory.CreateDirectory(targetDir);
string path = Path.Combine(targetDir, FileName);
file.SaveAs(path);
str = str + "/" + _FileName;
}
}
return "上传成功," + str;
}
else
return "文件不存在";
}
catch (Exception ex)
{
return "上传失败," + ex.Message;
}
}
客户端代码
}
///
///
///
///
///
/// 当存在文件时,是否替换,false:不替换,提示已存在,true直接替换
/// 保存的相对文件夹
///
public static string Upload(string url, string fileName, bool blnReplace = false, string strToDir = "Upload\\123\\456")
{
System.Net.ServicePointManager.Expect100Continue = false;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
Stream postStream = new MemoryStream();
#region 处理Form表单文件上传
//通过表单上传文件
string boundary = "----" + DateTime.Now.Ticks.ToString("x");
string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n";
try
{
//准备文件流
using (var fileStream = FileToStream(fileName))
{
var formdata = string.Format(formdataTemplate, "", Path.Combine(strToDir, System.IO.Path.GetFileName(fileName)) + (blnReplace ? "$1" : ""));
var formdataBytes = Encoding.UTF8.GetBytes(postStream.Length == 0 ? formdata.Substring(2, formdata.Length - 2) : formdata);//第一行不需要换行
postStream.Write(formdataBytes, 0, formdataBytes.Length);
//写入文件
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
postStream.Write(buffer, 0, bytesRead);
}
}
}
catch (Exception ex)
{
throw ex;
}
//结尾
var footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
postStream.Write(footer, 0, footer.Length);
request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
#endregion
request.ContentLength = postStream != null ? postStream.Length : 0;
request.Accept = "*/*";
//request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
request.KeepAlive = true;
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
#region 输入二进制流
if (postStream != null)
{
postStream.Position = 0;
//直接写入流
Stream requestStream = request.GetRequestStream();
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
{
requestStream.Write(buffer, 0, bytesRead);
}
postStream.Close();//关闭文件访问
}
#endregion
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader myStreamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")))
{
string retString = myStreamReader.ReadToEnd();
return retString;
}
}
}
public static Stream FileToStream(string fileName)
{
// 打开文件
FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
// 读取文件的 byte[]
byte[] bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, bytes.Length);
fileStream.Close();
// 把 byte[] 转换成 Stream
Stream stream = new MemoryStream(bytes);
return stream;
}
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string[] files = openFileDialog1.FileNames;
Thread th = new Thread(() =>
{
Log("进度:0/" + files.Length);
for (int i = 0; i < files.Length; i++)
{
string str = Upload("http://localhost:8344/uf.asmx/Upload_File", files[i]);
if (str.Contains("文件已存在"))
{
str = Upload("http://localhost:8344/uf.asmx/Upload_File", files[i], true);
}
Log("进度:" + (i + 1) + "/" + files.Length);
}
});
th.IsBackground = true;
th.Start();
}
}
private void Log(string msg)
{
if (this.label1.InvokeRequired)
{
this.label1.BeginInvoke(new MethodInvoker(delegate()
{
Log(msg);
}));
}
else
{
label1.Text = msg;
}
}