public void GetViewUrl(IFormFile file)
{
using (var client = new HttpClient())
{
//将文件转成流
var stream = file.OpenReadStream();
//请求体构建
var content = new MultipartFormDataContent();
content.Add(new StreamContent(stream), "file", file.FileName);
//发送请求
var response = client.PostAsync("url", content);
//请求成功,读取结果
if (response.Result.StatusCode == HttpStatusCode.OK)
{
var result = response.Result.Content.ReadAsStringAsync().Result;
//其他操作...
}
}
}
整体的代码很简单。这里遇到过一个问题,使用浏览器 form
标签上传文件的时候,请求头的 Content-Type
会自动添加 boundary
,它的作用可以看这篇博客。
我最开始写代码时,手动设置了 Content-Type
,然后 boundary
参数就没有了
content.Headers.ContentType = new MediaTypeHeaderValue("multipart/form");
实际上我们使用以下代码给请求体添加文件的时候,它会自动给 Content-Type
添加 multipart/form-data
和 boundary
content.Add(new StreamContent(stream), "file", file.FileName);
参考
【http/https】Content-Type 的 boundary - 粽先生 - 博客园 (cnblogs.com)