MVC中的下载文件及上传

前言:最近做的项目中用到了文件下载与上传,一下子想不起来,只能进行百度,为了方便自己做了一个小demo,特此写了这篇小笔记

1.页面方面:

MVC中的下载文件及上传_第1张图片

2.控制器方面

namespace MvcUpload.Controllers
{
    public class UploadOrDownLoadController : Controller
    {
        // GET: UploadOrDownLoad
        public ActionResult Upload() => View();//上传文件
        public ActionResult DownLoad() => View();
        [HttpPost]
        public ActionResult Upload(FormCollection from)
        {
            if (Request.Files.Count == 0)
                return View();

            var file = Request.Files[0];

            if (file.ContentLength == 0)
            {
                return View();
            }
            else
            {
                //文件大小不为0时
                string target = Server.MapPath("/") + "Learn/";
                string filename = file.FileName;
                string path = target + filename;
                file.SaveAs(path);
            }
            return View();
        }

        [HttpPost]
        public ActionResult DownLoad(string filename)
        {

            string filepath = Server.MapPath("/") + "Learn/" + filename;
            FileStream file = new FileStream(filepath, FileMode.Open);
            return File(file, "text/plain", filename);
        }
    }
}

3.视图方面

@{
    Layout = null;
}


@using (Html.BeginForm("Upload", "UploadOrDownLoad", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    选择上传文件:
    

}

  后续将会更新如何通过a标签post请求控制器.

你可能感兴趣的:(MVC中的下载文件及上传)