天天看點

MVC中的下載下傳檔案及上傳

前言:最近做的項目中用到了檔案下載下傳與上傳,一下子想不起來,隻能進行百度,為了友善自己做了一個小demo,特此寫了這篇小筆記

1.頁面方面:

MVC中的下載下傳檔案及上傳
MVC中的下載下傳檔案及上傳
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" }))
{
    <text>選擇上傳檔案:</text><input name="file" type="file" id="file" />
    <br />
    <br />
    <input type="submit" name="Upload" value="Upload" />
}
<form method="post" action="DownLoad?filename=aa.jpg">
    <input type="submit" name="Demo" value="下載下傳" />
</form>
      

  後續将會更新如何通過a标簽post請求控制器.