码迷,mamicode.com
首页 > Web开发 > 详细

asp.net core文件上传与下载

时间:2017-07-05 21:22:32      阅读:293      评论:0      收藏:0      [点我收藏+]

标签:extension   出图   文件上传与下载   download   result   utf8   private   ring   substr   

public class FileController : Controller { /// <summary> /// 跟asp.net webform和asp.net mvc不一样,通过注入的方式,获取项目所在路径 /// </summary> private IHostingEnvironment _hostEnv; public FileController(IHostingEnvironment env) { _hostEnv = env; //其他服务 } public IActionResult Index() { return View(); } /// <summary> /// 方式一 输出文本文件 /// </summary> /// <returns></returns> public IActionResult DownloadFile1() { var buffer = Encoding.UTF8.GetBytes("asp.net core download file"); return File(buffer, "text/plain", "file.txt"); } /// <summary> /// 方式二 输出文本文件 /// </summary> /// <returns></returns> public IActionResult DownloadFile2() { var stream = new MemoryStream(); var streamWriter = new StreamWriter(stream); streamWriter.Write("{\"content\":\"asp.net core download file\"}"); streamWriter.Flush(); stream.Seek(0, SeekOrigin.Begin); return File(stream, "text/plain", "file.json"); } /// <summary> /// 方式三 输出图片文件 /// </summary> /// <returns></returns> public IActionResult DownloadFile3() { var path = Path.Combine(_hostEnv.ContentRootPath, "UploadFile", "netcore5.png"); var fileExtensionName = Path.GetExtension(path); return PhysicalFile(path, "image/png", $"{DateTime.Now.ToString("yyyyMMddhhmmss")}.{fileExtensionName}"); } /// <summary> /// 多文件上传 /// </summary> /// <param name="files">文件上传的name</param> /// <returns></returns> public IActionResult UploadFile(IList<IFormFile> files) { if (files != null) { //处理多文件 foreach (var file in files) { //如果需要对文件处理,可以根据文件扩展名,进行筛选 var fileExtensionName = Path.GetExtension(file.FileName).Substring(1); var saveFilePath = Path.Combine(_hostEnv.ContentRootPath, "UploadFile", $"{DateTime.Now.ToString("yyyyMMddhhmmss")}.{fileExtensionName}"); var stream = new FileStream(saveFilePath, FileMode.Create); //asp.net core对异步支持很好,如果使用异步可以使用file.CopyToAsync方法 file.CopyTo(stream); } return Ok(); } else { return Ok(); } } }









<html>
<head> <title>文件上传</title> </head> <body> <form action="/File/UploadFile" enctype="multipart/form-data" method="post"> <input type="file" name="files" multiple /> <input type="submit" value="上传文件" /> </form> </body> </html>

 

asp.net core文件上传与下载

标签:extension   出图   文件上传与下载   download   result   utf8   private   ring   substr   

原文地址:http://www.cnblogs.com/tangjiansheng/p/7123265.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!