• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Leo-8-5-9-4
博客园    首页    新随笔    联系   管理    订阅  订阅

.net core 接收并存储客户端上传的文件

1 文件是上传到Host,非上传到阿里云OSS

2 在Program.cs或StartUp中使用静态文件的中间件

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{

app.UseStaticFiles();

}

.net core 创建的api项目中,会有一个wwwroot文件夹,在wwwroot文件夹我们创建一个image文件夹,image文件夹中有一个图片a.jpg,当中间件UseStaticFiles启用后,我们可以通过在浏览器上输入[ip]:[port]/image/a.jpg成功浏览图片。

 

3 Controller具体代码

 1 [HttpPost("UploadInvoiceFile")]
 2 public async Task<IActionResult> UploadFile(IFormFile file)
 3         {
 4             if (!new[] {"image/jpeg", "image/png", "application/pdf"}.Contains(file.ContentType))
 5                 return BadRequest("图片仅支持jpg和png格式,文件支持pdf");
 6 
 7 
 8             if (file is {Length: > 0})
 9                 try
10                 {
11                     var fileName = Path.GetFileName(file.FileName);
12 
13                     var staticFileRoot = "wwwroot";
14                     // 这里是文件路径,不包含文件名
15                     var fileUrlWithoutFileName =
16                         @$"InvoiceStaticFile\{DateTime.Now.Year}\{DateTime.Now.Month}\{DateTime.Now.Day}";
17 
18                     // 创建文件夹,如果文件夹已存在,则什么也不做
19                     Directory.CreateDirectory($"{staticFileRoot}/{fileUrlWithoutFileName}");
20 
21                     //string fileName = Path.GetFileName(postedFile.FileName);
22                     //using (FileStream stream = new FileStream(Path.Combine(path, fileName), FileMode.Create))
23                     //{
24                     //    postedFile.CopyTo(stream);
25                     //    uploadedFiles.Add(fileName);
26                     //    ViewBag.Message += string.Format("<b>{0}</b> uploaded.<br />", fileName);
27                     //}
28                     // 使用哈希的原因是前端可能传递相同的文件,服务端不想保存多个相同的文件
29 
30                     var hash = SHA256.Create();
31                     // 读取文件的流 把文件流转为哈希值
32                     var hashByte = await hash.ComputeHashAsync(file.OpenReadStream());
33                     // 再把哈希值转为字符串 当作文件的文件名
34                     var hashedFileName = BitConverter.ToString(hashByte).Replace("-", "");
35 
36                     // 重新获得一个文件名
37                     var newFileName = hashedFileName + "." + fileName.Split('.').Last();
38 
39                     var filePath = Path.Combine(Directory.GetCurrentDirectory(),
40                         $@"{staticFileRoot}\{fileUrlWithoutFileName}", newFileName);
41 
42                     await using var fileStream = new FileStream(filePath, FileMode.Create);
43                     await file.CopyToAsync(fileStream);
44                     return Created("", new {Name = fileName, Url = Path.Combine(fileUrlWithoutFileName, newFileName)});
45                 }
46                 catch (Exception e)
47                 {
48                     _logger.LogError(e, "保存文件出错。错误消息:" + e.Message);
49                     throw;
50                 }
51 
52             return BadRequest("请上传文件");
53         }

 

 

     

posted on 2022-02-15 22:22  Leo-8-5-9-4  阅读(415)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3