C# 通過http post 請求上傳圖片和參數


一、C# Winform或控制台

 1 /// <summary>
 2         /// 通過http上傳圖片及傳參數
 3         /// </summary>
 4         /// <param name="imgPath">圖片地址(絕對路徑:D:\demo\img\123.jpg)</param>
 5         public void UploadImage(string imgPath)
 6         {
 7             var uploadUrl = "http://localhost:3020/upload/imgup";
 8             var dic = new Dictionary<string, string>() {
 9                     {"para1",1.ToString() },
10                     {"para2",2.ToString() },
11                     {"para3",3.ToString() },
12                 };
13             var postData = Utils.BuildQuery(dic);//轉換成:para1=1&para2=2&para3=3
14             var postUrl = string.Format("{0}?{1}", uploadUrl, postData);//拼接url
15             HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
16             request.AllowAutoRedirect = true;
17             request.Method = "POST";
18 
19             string boundary = DateTime.Now.Ticks.ToString("X"); // 隨機分隔線
20             request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
21             byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
22             byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
23 
24             int pos = imgPath.LastIndexOf("\\");
25             string fileName = imgPath.Substring(pos + 1);
26 
27             //請求頭部信息 
28             StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
29             byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
30 
31             FileStream fs = new FileStream(imgPath, FileMode.Open, FileAccess.Read);
32             byte[] bArr = new byte[fs.Length];
33             fs.Read(bArr, 0, bArr.Length);
34             fs.Close();
35 
36             Stream postStream = request.GetRequestStream();
37             postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
38             postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
39             postStream.Write(bArr, 0, bArr.Length);
40             postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
41             postStream.Close();
42 
43             HttpWebResponse response = request.GetResponse() as HttpWebResponse;
44             Stream instream = response.GetResponseStream();
45             StreamReader sr = new StreamReader(instream, Encoding.UTF8);
46             string content = sr.ReadToEnd();
47         }

二、圖片接收接口

[ValidateInput(false)]
        public JsonResult imgup(string para1,string para2,string para3)
        {
            if (Request.Files.Count > 0)
            {
                //傳過來的圖片
                var file = Request.Files[0];
                //保存到本地或服務器

            }
            return new JsonResult { };
        }
 1  /// <summary>
 2         /// 上傳圖片信息
 3         /// </summary> 
 4         /// <returns></returns>
 5         [ValidateInput(false)]
 6         public JsonResult ImgUp()
 7         {
 8             try
 9             {
10                 if (Request.Files.Count > 0)
11                 {
12                     HttpPostedFileBase file = Request.Files[0];
13                     string path = file.FileName;//獲取Execle文件名    
14                     string IsXls = System.IO.Path.GetExtension(path).ToString().ToLower();
15                     string fileName = DateTime.Now.ToString("yyyyMMddhh") + IsXls;
16                     string savePath = Server.MapPath(("~\\Upload\\") + fileName);//Server.MapPath 獲得虛擬服務器相對路徑
17                     file.SaveAs(savePath); //SaveAs 將上傳的文件內容保存在服務器上 
18                 }
19                 return Json(new { Success = true, Message = "成功" }, JsonRequestBehavior.AllowGet);
20             }
21             catch (Exception ex)
22             {
23                 return Json(new { Success = false, Message = "失敗" }, JsonRequestBehavior.AllowGet);
24             }
25         }

 轉自連接:https://www.cnblogs.com/pingming/p/8550802.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM