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 == )
return View(); var file = Request.Files[]; if (file.ContentLength == )
{
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请求控制器.

上一篇:Docker资源网站收藏


下一篇:Linux 虚拟内存和物理内存的理解