WPF基于httpclient下文件的上传和下载

文件上传


 

       /// 


        /// 上传文件
        /// 

        ///  api地址
        ///  上传文件路径
        ///  其他api要求数据(例如文件格式.jpg.rar.exe....)
        /// 
        public static string UploadResponseMulitipart(string url, string filePath, string postData)
        {
            string result = string.Empty;
            try
            {
                using (HttpClient httpClient = new HttpClient())
                {
                    using (var multipartFormDataContent = new MultipartFormDataContent())
                    {
                        string fileName = Path.GetFileNameWithoutExtension(filePath);
                        var fileContent = new ByteArrayContent(File.ReadAllBytes(filePath));
                        fileContent.Headers.Add("Content-Type", "multipart/form-data");
                        multipartFormDataContent.Add(fileContent, "file", fileName);
                        var body = new StringContent(postData, Encoding.UTF8, "application/json");
                        multipartFormDataContent.Add(body, "fileType");
                        var response = httpClient.PostAsync(url, multipartFormDataContent).Result;
                        //确保Http响应成功
                        if (response.IsSuccessStatusCode)
                        {
                            //异步读取json
                            result = response.Content.ReadAsStringAsync().Result;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Instance.Log($"http post error, url={url},exception:{e}", Category.Error);
            }

            return result;
        }


文件下载

        ///


        /// Downs the load file.
        ///

        /// api地址
        /// 文件保存路径
        ///
        public static async Task DownLoadFile(string url, string savePath)
        {
            string newFileName = savePath;
            using (HttpClient httpClient = new HttpClient())
            {
                try
                {
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    HttpResponseMessage response = httpClient.GetAsync(url).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        var ms = await response.Content.ReadAsStreamAsync();
                        using (var br = new BinaryReader(ms))
                        {
                            var data = br.ReadBytes((int)ms.Length);
                            File.WriteAllBytes(newFileName, data);

                        }
                    }
                }
                catch (Exception e)
                {
                    Logger.Instance.Log($"http get error,url={url},exception:{e}", Category.Error);
                }
            }
            return newFileName;
        }

你可能感兴趣的:(C#,wpf)