一、单文件上传
1、文件接口
注意这里IFormFIle file,必须与postman上传文件的key值一样,不能是别的名字
[HttpPost]
public List<Student> Get(IFormFile file)
{
//学生集合
List<Student> lists = new List<Student>();
//打开文件stream
Stream stream = file.OpenReadStream();
//操纵stream,生成集合
var rows = stream.Query<Student>().ToList();
//将两个excel合并为一个集合
lists = lists.Union(rows).ToList();
//批量添加数据
_studentDbContext.Student.AddRange(lists);
//保存数据
_studentDbContext.SaveChanges();
return lists;
}
}
2、student
using System.ComponentModel.DataAnnotations;
namespace _02_EFWithOptionExcel
{
public class Student
{
public int ID { get; set; }
public string Name { get; set; }
public string Sex { get; set; }
public string Phone { get; set; }
public string Address { get; set; }
}
}
3、Postman
4、excel
二、多文件上传
student实体一样
1.controller
IFormCollection 文件集合
[HttpPost]
public List<Student> Get( IFormCollection formCollection)
{
//文件集合
FormFileCollection fileCollection = (FormFileCollection)formCollection.Files;
//学生集合
List<Student> lists = new List<Student>();
//遍历集合中的文件
foreach (IFormFile file in fileCollection)
{
//打开文件stream
Stream stream = file.OpenReadStream();
//操纵stream,生成集合
var rows = stream.Query<Student>().ToList();
//将两个excel合并为一个集合
lists = lists.Union(rows).ToList();
}
//批量添加数据
_studentDbContext.Student.AddRange(lists);
//保存数据
_studentDbContext.SaveChanges();
return lists;
}
2.postman
三、下载文件功能
//伪码
[Route("fileDownload")]
[HttpGet]
public async Task<IActionResult> FileDownLoadAsync([FromQuery]FileDownloadRequest request)
{
//这里file接收的是文件流,类型是memoryStream(内存流)
var file = await _exportApi.FileDownLoadAsync(request);
//
using (var sw = file.Content)
{
//把流读取到一个字节数组内
var bytes = new byte[sw.Length];
sw.Read(bytes, 0, bytes.Length);
sw.Close();
//这里是对于从别处读取的文件的文件名会被url编码,这里是进行反解码
var filename = System.Web.HttpUtility.UrlDecode(file.ContentHeaders.ContentDisposition.FileName, Encoding.UTF8);
//返回文件流,参数,字节数组,传输的Content格式,文件名
return File(bytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",filename);
}
}