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