zoukankan      html  css  js  c++  java
  • MVC中的下载文件及上传

    前言:最近做的项目中用到了文件下载与上传,一下子想不起来,只能进行百度,为了方便自己做了一个小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请求控制器.

  • 相关阅读:
    GDUFE ACM-1020
    GDUFE ACM-1069(简单的巴什博弈)
    GDUFE ACM-1138
    GDUFE ACM-1009
    GDUFE ACM-1008
    GDUFE ACM-1005
    LCA 最近公共祖先
    51nod
    51nod
    51nod
  • 原文地址:https://www.cnblogs.com/ZaraNet/p/9547581.html
Copyright © 2011-2022 走看看