asp.net core文件上传与下载
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>