ASP.NET MVC实现简单的文件上传与下载

原文链接:https://blog.csdn.net/pan_junbiao/article/details/80718784?depth_1-utm_source=distribute.pc_relevant_right.none-task&utm_source=distribute.pc_relevant_right.none-task

上传文件HTML

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

 

下载文件HTML

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

 

创建FileController.cs后台控制器

public class FileController : Controller
{
    /// <summary>
    /// 上传文件
    /// </summary>
    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("上传成功");
    }
 
    /// <summary>
    /// 下载文件
    /// </summary>
    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);
    }
}

 

posted @ 2020-03-17 14:05  萌橙  阅读(552)  评论(1编辑  收藏  举报