C# HttpClient Post 參數同時上傳文件 上傳圖片 調用接口


// 調用接口上傳文件
using (var client = new HttpClient())
{
    using (var multipartFormDataContent = new MultipartFormDataContent())
    {
        var values = new[]
        {
            new KeyValuePair<string, string>("a", "3"),
            new KeyValuePair<string, string>("c", "2"),
            new KeyValuePair<string, string>("d", "2")
             //other values
        };
 
        foreach (var keyValuePair in values)
        {
            multipartFormDataContent.Add(new StringContent(keyValuePair.Value),
                String.Format("\"{0}\"", keyValuePair.Key));
        }
 
        multipartFormDataContent.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(@"D:\test.jpg")),
            "\"pic\"",
            "\"test.jpg\"");
 
        var requestUri = "http://localhost:8080";
        var html = client.PostAsync(requestUri, multipartFormDataContent).Result.Content.ReadAsStringAsync().Result;
    }
}

 

API 接口,接收請求參數 和上傳的文件

 

   public string UploadHeadImg()
        {

            var ts = HttpContext.Current.Request["d"];
            HttpPostedFile file = System.Web.HttpContext.Current.Request.Files[0];
            // 文件擴展名
            string fileExtension = Path.GetExtension(file.FileName).ToLower();    
    
            Stream sr = file.InputStream;//頭像文件流
            Bitmap bitmap = (Bitmap)Bitmap.FromStream(sr);
            bitmap.Save(“c:/img/1.jpg”, System.Drawing.Imaging.ImageFormat.Jpeg);
          return "success";
        }

 

來源:https://blog.csdn.net/luofeng0710/article/details/84202008

 


免責聲明!

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



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