C# 上传文件,并修改文件名称
需要用到的 包 文件

安装
-
在
NuGet中搜索NPOI -
双击项目名称,在下面添加代码
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="NPOI" Version="2.7.1" />
</ItemGroup>
添加命名空间
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel; // 对于 .xlsx 格式
using NPOI.HSSF.UserModel; // 对于 .xls 格式
添加Controller方法
[HttpPost]
public IActionResult Upload(IFormFile file)
{
ApiResult backMgs = new ApiResult();
if (file == null || file.Length == 0)
{
return Content("请选择一个文件上传。");
}
//设置保存文件路径 uploads + 时间
string filePaths = $"\\wwwroot\\files\\{DateTime.Today:yyyyMMdd}";
//配置全路径
string rootPath = $"{Directory.GetCurrentDirectory()}{filePaths}";
//判断是否有当前路径,没有则创建
if (!Directory.Exists(rootPath))
{
Directory.CreateDirectory(rootPath);
}
//获取文件后缀名
string sExt = Path.GetExtension(file.FileName).ToLower();
//新文件名称
string newFileName = $"ART{DateTime.Now:yyyyMMddHHmmss}{new Random(Guid.NewGuid().GetHashCode()).Next(100, 999)}{sExt}";
// 设置新文件完整路径
string path = Path.Combine(rootPath, newFileName);
// 保存文件
using (var stream = new FileStream(path, FileMode.Create))
{
file.CopyTo(stream);
}
// 返回相关信息
return Ok("...");
}
浙公网安备 33010602011771号