后台代码
public class FileController : Controller
{
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}");
}
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);
file.CopyTo(stream);
}
return Ok();
}
else
{
return Ok();
}
}
}
html文件上传
<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>