C# 通过HttpClient 发送及接收文件

Client端:

public static UploadMediaResponseModel HttpRequest(string url, UploadMediaRequestModel requestParam, HttpMethod method, string refName)
        {
            var request = new HttpRequestMessage(method, url);

            var mediaContent = new MultipartFormDataContent();
            mediaContent.Add(new ByteArrayContent(requestParam.binary_media_data), "binary_media_data", refName);//此处ByteArrayContent内的比特流也可以直接从本地文件读取
            request.Content = mediaContent;
            var httpClient = new HttpClient();
            var response = httpClient.Send(request);
            if (response.IsSuccessStatusCode)
            {
                var resString = response.Content.ReadAsStringAsync().Result;
                return JsonConvert.DeserializeObject<UploadMediaResponseModel>(resString);
            }
            else
            {
                throw new HttpRequestException($"HttpClientBusiness.HttpRequest error,url:{url}/{method},param:{JsonConvert.SerializeObject(requestParam)},response:JsonConvert.SerializeObject(response)");
            }
        }

 

Server端:

public void UploadImg() 
        {
            var savePath= $"{Directory.GetCurrentDirectory()}/test/";
            using (FileStream output = new FileStream(savePath + Request.Form.Files[0].FileName, FileMode.Create))
            {
                Request.Form.Files[0].CopyTo(output);
            }
        }

 

posted @ 2022-04-02 15:02  along_bro  阅读(1467)  评论(0编辑  收藏  举报