asp.net core文件上传与下载
2021-07-03 21:05
阅读:694
YPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
标签:extension 出图 文件上传与下载 download result utf8 private ring substr
public class FileController : Controller { ////// 跟asp.net webform和asp.net mvc不一样,通过注入的方式,获取项目所在路径 /// private IHostingEnvironment _hostEnv; public FileController(IHostingEnvironment env) { _hostEnv = env; //其他服务 } public IActionResult Index() { return View(); } /// /// 方式一 输出文本文件 /// /// public IActionResult DownloadFile1() { var buffer = Encoding.UTF8.GetBytes("asp.net core download file"); return File(buffer, "text/plain", "file.txt"); } /// /// 方式二 输出文本文件 /// /// 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"); } /// /// 方式三 输出图片文件 /// /// 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}"); } /// /// 多文件上传 /// /// 文件上传的name /// public IActionResult UploadFile(IList 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(); } } } 文件上传
asp.net core文件上传与下载
标签:extension 出图 文件上传与下载 download result utf8 private ring substr
原文地址:http://www.cnblogs.com/tangjiansheng/p/7123265.html
评论
亲,登录后才可以留言!