MVC 文件上传下载

上传前端页面

<form action='@Url.Action("Upload", "File")' method="post" enctype="multipart/form-data">
    <input type="file" name="file" /><br />
    <input type="submit" value="提交" />
</form>

下载前端页面

<a href='@Url.Action("Download", "File", new { fileName = "MyPhoto.png" })'>下载文件</a>

控制器方法

public class FileController : Controller
{
// 上传文件
public ActionResult Upload(HttpPostedFileBase file)
{
var fileName = file.FileName;
var filePath = Server.MapPath(string.Format("~/{0}", "File"));
file.SaveAs(Path.Combine(filePath, fileName));
return Json("上传成功");
}
// 下载文件
public FileStreamResult Download(string fileName)
{
string filePath = Server.MapPath(string.Format("~/{0}/{1}", "File", fileName));
FileStream fs = new FileStream(filePath, FileMode.Open);
return File(fs, "text/plain", fileName);
}
}

原文地址:https://www.cnblogs.com/lls-995/p/13360956.html