通过App, 网页或小程序上传文件到服务器上常见的一个功能,本文演示如何在 .NET Core 3 中实现文件上传的 WebApi。
为简化案例,突出服务端接收文件的基本功能,本例中并不会把上传的文件存入到数据库中,而是简单的保存在服务端的特定目录下。
实现 Post 方法 我们使用一个 Http Post 方法来接收用户上传的文件。 在 .NET Core 中,要接收到文件,只需要将方法的参数设置为: IFormFile 类型即可。 如下:
1 2 public async Task<ApiResult> UploadFile (IFormFile file ) {}
文件上传到服务器上后,实际上存放在临时文件中的,我们通过 IFormFile 可以访问到该文件。 在接下来的代码中,我们将建立一个本地目录,并为上传的文件准备要给随机的文件名,然后把上传的文件内容复制到新文件中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 [HttpPost ] public async Task<ApiResult> UploadFile (IFormFile file ) { string fileName; ApiResult result = new ApiResult(); _logger.LogDebug("UploadFile, fileName = {0}" , file.FileName); try { var extension = "." + file.FileName.Split('.' )[file.FileName.Split('.' ).Length - 1 ]; fileName = DateTime.Now.Ticks + extension; var pathBuilt = Path.Combine(Directory.GetCurrentDirectory(), UPLOAD_FOLDER); if (!Directory.Exists(pathBuilt)) { Directory.CreateDirectory(pathBuilt); } var path = Path.Combine(Directory.GetCurrentDirectory(), UPLOAD_FOLDER, fileName); using (var stream = new FileStream(path, FileMode.Create)) { await file.CopyToAsync(stream); } result.Succ = true ; } catch (Exception e) { _logger.LogDebug("fail to write file" , e); } return result; }
完整的代码 上传类的完整代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 using System;using System.IO;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.AspNetCore.Mvc;using Microsoft.Extensions.Logging;using System.Net.Http;using System.Text.Json;using System.Security.Cryptography; using Microsoft.AspNetCore.Http;using Microsoft.AspNetCore.Http.Features;using WxServer.Model;using WxServer.ApiVo;namespace WxServer.Controllers { [ApiController ] [Route("/api/v1/product/check/photo" ) ] public class ProductController : ControllerBase { const string UPLOAD_FOLDER = "Upload\\files" ; private readonly ILogger<ProductController> _logger; public ProductController (ILogger<ProductController> logger ) { _logger = logger; } [HttpPost ] public async Task<ApiResult> UploadFile (IFormFile file ) { string fileName; ApiResult result = new ApiResult(); _logger.LogDebug("UploadFile, fileName = {0}" , file.FileName); try { var extension = "." + file.FileName.Split('.' )[file.FileName.Split('.' ).Length - 1 ]; fileName = DateTime.Now.Ticks + extension; var pathBuilt = Path.Combine(Directory.GetCurrentDirectory(), UPLOAD_FOLDER); if (!Directory.Exists(pathBuilt)) { Directory.CreateDirectory(pathBuilt); } var path = Path.Combine(Directory.GetCurrentDirectory(), UPLOAD_FOLDER, fileName); using (var stream = new FileStream(path, FileMode.Create)) { await file.CopyToAsync(stream); } result.Succ = true ; } catch (Exception e) { _logger.LogDebug("fail to write file" , e); } return result; } } }