C# HttpClient Post 参数同时上传文件 上传图片 调用接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 调用接口上传文件
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 接口,接收请求参数 和上传的文件

 

1
2
3
4
5
6
7
8
9
10
11
12
13
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

 

posted @   星辰与大海  阅读(8010)  评论(1编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示