I'm the gatekeeper of my own destiny

导航

winform采用POST上传指定文件,并获取返回值

      由于最近有个项目需要批量上传到服务器,并以一定的规则过滤上传数据。故做了个C#小程序来实现。该方法也是借鉴了网上的方法,并精简了代码。废话少说,来看代码。

      Web端代码

代码
 1 public partial class transform : System.Web.UI.Page
 2 {
 3     string path = "E:\\test\\uploadfi";
 4     protected void Page_Load(object sender, EventArgs e)
 5     {
 6       
 7         if (!string.IsNullOrEmpty(Request["fileName"]))
 8         {
 9            Response.Write(UploadFileWithString(Request["fileName"], Request.InputStream));
10             //Response输出返回值
11             
12         }
13     }
14 
15 
16     protected string UploadFileWithString(string fileName,Stream streams)
17     {
18         
19          byte[] b = new byte[Convert.ToInt32( streams.Length)];
20          streams.Read(b, 0, Convert.ToInt32(streams.Length));
21         
22         string creatpath = path + "\\sh";
23         MemoryStream ms = new MemoryStream(b);          
24          if (!Directory.Exists(creatpath))
25             Directory.CreateDirectory(creatpath);
26         try
27         {
28             FileStream fs = new FileStream(creatpath + "\\" + fileName, FileMode.Create);
29             ms.WriteTo(fs);
30             ms.Close();
31             fs.Close();
32             return "1";
33         }
34         catch
35         {
36             return "0";
37         }
38     }

 

 

      winform端代码

    

代码
 1  private void button2_Click(object sender, EventArgs e)
 2         {
 3             
 4             if (openFileDialog1.ShowDialog() == DialogResult.OK)
 5                 label2.Text = openFileDialog1.FileName;
 6             FileInfo f = new FileInfo(openFileDialog1.FileName);
 7             WebUpload(openFileDialog1.SafeFileName, f);
 8          
 9         }
10  protected void WebUpload(string fileName, FileInfo f)
11         {
12             WebClient webc = new WebClient();
13             FileStream fs = new FileStream(f.FullName, FileMode.Open, FileAccess.Read);
14             byte[] byteString=new byte[f.Length];
15             fs.Read(byteString, 0,Convert.ToInt32(f.Length));
16             fs.Close();
17             
18             byte[] returnVal = webc.UploadData("http://localhost/sz/transform.aspx?fileName="+HttpUtility.UrlEncode(fileName,Encoding.GetEncoding("gb2312")), "post",byteString);
19             
20             MessageBox.Show(Encoding.GetEncoding("gb2312").GetString(returnVal));//返回值
21             
22         }

 

    

     

posted on 2011-02-15 11:00  Wishbay  阅读(872)  评论(0编辑  收藏  举报