首先我们需要创建一个form表单如下:

<form method="post" enctype="multipart/form-data" asp-controller="UpLoadFile" asp-action="FileSave">

<div>

<div>

<p>Form表单多个上传文件:</p>

<input type="file" name="files" multiple />

<input type="submit" value="上传" />

</div>

</div>

</form>

private IHostingEnvironment _hostingEnvironment;
public HomeController(IHostingEnvironment hostingEnvironment)
{

_hostingEnvironment = hostingEnvironment;
}

//[RequestSizeLimit(100_000_000)] //最大100m左右
//[DisableRequestSizeLimit] //或者取消大小的限制
public IActionResult Upload()
{
var files = Request.Form.Files;

long size = files.Sum(f => f.Length);

string webRootPath = _hostingEnvironment.WebRootPath;

string contentRootPath = _hostingEnvironment.ContentRootPath;
List<string> filenames=new List<string>();
foreach (var formFile in files)

{

if (formFile.Length > 0)

{
string fileExt = Path.GetExtension(formFile.FileName); //文件扩展名,不含“.”

long fileSize = formFile.Length; //获得文件大小,以字节为单位

string newFileName = System.Guid.NewGuid().ToString()+ fileExt; //随机生成新的文件名

var filePath = webRootPath + "/upload/";
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
using (var stream = new FileStream(filePath+ newFileName, FileMode.Create))

{
formFile.CopyTo(stream);
}
filenames.Add(newFileName);
}

}

return Ok(new { filenames, count = files.Count,size });
}
public IActionResult DownLoad(string file)

{
string webRootPath = _hostingEnvironment.WebRootPath;
var addrUrl = webRootPath+"/upload/"+ file;

var stream = System.IO.File.OpenRead(addrUrl);

string fileExt = Path.GetExtension(file);

//获取文件的ContentType

var provider = new FileExtensionContentTypeProvider();

var memi = provider.Mappings[fileExt];

return File(stream, memi, Path.GetFileName(addrUrl));

}

public IActionResult DeleteFile(string file)
{
string webRootPath = _hostingEnvironment.WebRootPath;
var addrUrl = webRootPath + "/upload/" + file;
if (System.IO.File.Exists(addrUrl))
{
//删除文件
System.IO.File.Delete(addrUrl);
}
return Ok(new { file });
}

最新文章

  1. C# 类:类型 , 数学:类型
  2. 【Java基础】枚举和注解
  3. how-to-redirect-cin-and-cout-to-files
  4. Android 通知栏Notification的整合 全面学习 (一个DEMO让你完全了解它)
  5. Server 2003序列号
  6. 3. c的输入输出
  7. PHP截取中文字符串
  8. C#中子窗体获取父窗体中控件的内容
  9. javascript——touch事件介绍与实例演示
  10. css3字体
  11. 开发MOSS自定义字段类型
  12. Java的JDBC原生态学习以及连接池的用法
  13. 输入三个整数x、y、z,请把这三个数由小到大输出
  14. java实现单链表反转(倒置)
  15. 如何屏蔽SkylineGlobe提供的三维地图控件上的快捷键
  16. 自学Zabbix3.12.4-动作Action-Operation配置
  17. 去除移动端alert/confirm的网址(url)
  18. private static final Logger logger= LoggerFactory.getLogger(WhMainBusi.class);
  19. 在idea中关闭vim模式
  20. java从文件中读取数据然后插入到数据库表中

热门文章

  1. MYSQL优化&mdash;&mdash;索引覆盖
  2. 数据库MySQL之 视图、触发器、存储过程、函数、事务、数据库锁、数据库备份、事件
  3. 7. Smali基础语法总结
  4. 不用EL表达式---实现product页面显示
  5. javax.servlet.jsp.PageContext cannot be resolved to a type
  6. struct stat中的mode_t
  7. Android之AlterDialog介绍
  8. ajax data参数
  9. 【转】Android自定义控件(二)——有弹性的ScrollView
  10. 将以太坊封装为 ERC20