文件上傳和導入 控制器代碼 [Route("api/[controller]")] [ApiController] public class UpdController : ControllerBase { private readonly IWebHostEnvironment env; priv ...
[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