1. 程式人生 > >MVC中的下載文件及上傳

MVC中的下載文件及上傳

form public 做的 rdo mode 前言 you 控制 req

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

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" }))
{
    <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請求控制器.

MVC中的下載文件及上傳