- IFormFile 使用可以看官方文档
- 上传端(客户端),通过文件流的方式 进行上传调用接口 POST
MultipartFormDataContent构造参数和文件对象 public async Task> UploadTestAsync()
{
var fileAdd = @"D:UploadReport中国调查报告-张某某(绿灯).doc";
FileStream fileStream = new FileStream(fileAdd, FileMode.Open);
using (var multipartContent = new MultipartFormDataContent())
{
//multipartContent.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(fileAdd)), "File", "中国调查报告(绿灯).doc");
//文件对象 File 需要接受方的参数一致
multipartContent.Add(new StreamContent(fileStream), "File", @"调查报告-张某某(绿灯).doc");
// 构建其他上传参数
multipartContent.Add(new StringContent("CS21040800001"), "OrderId");
multipartContent.Add(new StringContent("测试版本"), "ReprotVersion");
multipartContent.Add(new StringContent("测试"), "BusinessOrigin");
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("http://IP:7123");
return await httpClient.PostAsync("/XXX/File/UploadAsync", multipartContent);
}
}
}
- 上传文件接口:服务端(接受端) 接受上传文件流 IFormFile接受文件对象
public async Task UploadAsync([FromForm] FileReportDto fileModel)
{
//需要存储文件
var filefullPath = @"D:UploadReport中国调查报告-张某某1(绿灯)3.doc";
using (FileStream fs = new FileStream(filefullPath, FileMode.Create))
{
fileModel.File.CopyTo(fs);
fs.Flush();
}
//拿到文件流可以做其他操作 ,结合自己业务
}
// FileReportDto 对象
public class FileReportDto
{
///
///
///
public string OrderId { get; set; }
///
/// 报告文件对象
///
public IFormFile File { get; set; }
///
///
///
public string ReprotVersion { get; set; }
///
///
///
public string BusinessOrigin { get; set; }
}
- 下载文件接口 (文件流方式)
public async Task DownStreamAsync(string orderId)
{
try
{
//获取文件信息 ,自己的业务
//下载文件
using (WebClient wclient = new WebClient())
{
//从远程获取文件流(本地也可以获取),参考客户端方法
var fileStream = wclient.OpenRead(https://devblogs.microsoft.com/dotnet/wp-content/uploads/sites/10/2019/05/dotnet5_platform.png);
//获取文件扩展名,并返回对应的文件类型
var ext = fileResult.FileName.Substring(fileResult.FileName.LastIndexOf("."));
new FileExtensionContentTypeProvider().Mappings.TryGetValue(ext, out var contenttype);
return File(fileStream, contenttype ?? "application/octet-stream", fileResult.FileName);
}
}
catch (Exception ex)
{
_nLogHelper.Error($"下载异常【】,{ex.Message}");
return new JsonResult(new ReturnResult { IsSuccess = false, Message = $"下载异常:{ex.Message}", Data = $"" });
}
}