winform 利用Http向服务器上传与下载文件

  利用在服务器端的IIS,布置“请求处理映射”。从而处理,本地发出Post请求。Url指向web网站所在路径的请求映射。由映射代码实现服务器保存文件。

  winform里面使用,WebClient的对象,完成Url请求;

  

winform代码:文件保存的地址为服务器网站根目录下的files文件夹(需要提前创建)/

 OpenFileDialog fileDialog = new OpenFileDialog
            {
                Multiselect = false,
                Title = "请选择文件",
                Filter = "所有文件(*.*)|*.*"
            };
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    string path = Path.GetFullPath(fileDialog.FileName);                             //绝对路径         //显示文件路径
                    string fileName = Path.GetFileName(fileDialog.FileName);
                    WebClient wc = new WebClient();
                    wc.Credentials = CredentialCache.DefaultCredentials;
                    wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                    wc.QueryString["fname"] = fileDialog.SafeFileName;
                    byte[] fileb = wc.UploadFile(new Uri(@"http://localhost/test.ts"), "POST", path);
                    string res = Encoding.GetEncoding("gb2312").GetString(fileb);
                   
                    
                    //文件名上传到数据库
                    if (DataBaseHelper.UpLoadFileName(fileName))
                    {
                        MessageBox.Show(fileName + "上传成功");
                    }
                    else
                    {
                        MessageBox.Show(fileName + "上传失败");
                    }
                 
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message + "上传失败");
                }

            }

目标服务器的 映射处理代码:

public void ProcessRequest(HttpContext context)
        {
            //在此处写入您的处理程序实现。
            context.Response.ContentType = "text/plain";
            try
            {
                HttpFileCollection files = context.Request.Files;
                if (files.Count > 0)
                {
                    files[0].SaveAs(HttpContext.Current.Server.MapPath("files/" + context.Request.QueryString["fname"]));
                    context.Response.Write("save success!");
                }
                else
                    context.Response.Write("hello request!");
            }
            catch (Exception ex)
            {
                context.Response.Write("save error!" + ex.Message);
            }
        }

客户端下载文件:

 FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                for (int i = 0; i < dgvContactInfo.Rows.Count; i++)
                {
                    

                    DataGridViewCheckBoxCell cb = (DataGridViewCheckBoxCell)this.dgvContactInfo.Rows[i].Cells[0];
                    bool flag = Convert.ToBoolean(cb.Value);

                    if (flag == true)
                    {
                        try
                        {
                            string fileName = dgvContactInfo.Rows[i].Cells[1].Value.ToString();


                            string path = folderBrowserDialog1.SelectedPath;
                            WebClient wc = new WebClient();
                            //wc.Credentials = CredentialCache.DefaultCredentials;
                            wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                            string fileUrl = @"http://localhost/files/" + fileName;

                            wc.DownloadFile(new Uri(fileUrl), string.Format(@"{0}{1}", path, fileUrl.Substring(fileUrl.LastIndexOf('/') + 1)));
                           
                        }
                        catch
                        {
                            
                        }
                    }
                }

btw:

记得修改请求限制。我就是没修改限制,导致测试的时候一直失败,以为这个方法不行。

修改根目录的Web.config 文件里面的     <httpRuntime maxRequestLength="2048000" executionTimeout="600"/> 和 iis的配置文件,可以解除上传的文件的大小限制

建议去MSDN阅读以下,关于IIS 的“模块”和“处理程序映射”文章,里面详细介绍了如何使用 映射;

从大佬的文章中窃取的代码:https://www.cnblogs.com/farmer-y/p/6179242.html

原文地址:https://www.cnblogs.com/ILoveMyJob/p/9400117.html