利用在服務器端的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