- A+
所属分类:.NET技术
文件上传和导入
控制器代码
[Route("api/[controller]")]
[ApiController]
public class UpdController : ControllerBase
{
private readonly IWebHostEnvironment env;
private readonly IUserRespository userRespository;
public UpdController(IWebHostEnvironment env, IUserRespository userRespository)
{
this.env = env;
this.userRespository = userRespository;
}
[HttpPost]
public IActionResult Upload(IFormFile formFile)
{
//先上传 才能将内容导入数据库
//var file = request.Form.Files[0]
//判断扩展名 要求只能上传 excel 获取文件扩展名 引用system.IO
//判断文件扩展名为.xls(2003以前版本).xlsx(2007以后版本含2007)
var ext = Path.GetExtension(formFile.FileName);
if (ext == ".xls" || ext == ".xlsx")
{
try
{
//判断文件大小
//存储路径
var path = Path.Combine(env.ContentRootPath, "Images");
//判断文件夹是否存在
if (!Directory.Exists(path))
{
//创建文件夹
Directory.CreateDirectory(path);
}
//文件的名称
var newName = DateTime.Now.ToString("yyyyMMddHHmmss") + ext;
//把文件名和路径合并
var pathName = Path.Combine(path, newName);
//通过流的方式传递文件内容
using (var stream = new FileStream(pathName, FileMode.Create))
{
formFile.CopyTo(stream);
}
//////导入
ImportData(pathName);
//返回当前的IP地址和端口号路径和文件名
return Ok(new { oleName = formFile.FileName, url = "http://localhost:56405/StaticFiles/" + newName, size = formFile.Length });
}
catch (Exception)
{
throw;
}
}
else
{
return BadRequest("无效文件");
}
}
private bool ImportData(string path)
{
try
{
//找到文件打开
using (var stream = System.IO.File.OpenRead(path))
{
//获取的是一个集合
var rows = stream.Query<User>();
//调用批量添加的方法
return userRespository.AddBatchUser(rows);
}
}
catch (Exception)
{
throw;
}
}
}
NuGet包
Install-Package MiniExcel -Version 1.26.2
参考网站
https://gitee.com/dotnetchina/MiniExcel