C# Net 使用 HttpClient 上传文件及信息(带Headers,FormData参数)


C# Net 使用 HttpClient 上传文件及信息(带Headers,FormData参数)

 

包:Newtonsoft.Json

 

public static string UploadFile(byte[] file, string fileName, string token)
        {
            Uri uri = new Uri(Appsettings.App("FileServe") + "/file/upload");

            using (MemoryStream memoryStream = new MemoryStream(file))
            {
                var formData = new MultipartFormDataContent();
                formData.Headers.Add("Access-Token", token);
                formData.Add(new StreamContent(memoryStream, (int)memoryStream.Length), "file", fileName);

                //Region为请求文件接口需要的参数,根据调用接口参数而定
                //formData.Add(new StringContent(info.Region), "Region");

                var _httpclient = new HttpClient();
                var response = _httpclient.PostAsync(uri, formData).Result;
                if (response.IsSuccessStatusCode)
                {
                    var responseStr = response.Content.ReadAsStringAsync().Result;

                    JObject o = JObject.Parse(responseStr);
                    //var responseObj = JsonConvert.DeserializeObject<string>(responseStr);
                    if (o.ContainsKey("id"))
                    {
                        var id = o.GetValue("id").ToString();
                        return id;
                    }
                    else
                    {
                        throw new Exception("上传文件时出错,错误信息为:" + responseStr);
                    }
                }
            }
            return string.Empty;
        }

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM