• 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请求控制器.

  • 相关阅读:
    全国疫情数据的爬取
    Spring_声明式事务
    第三周总结
    Spring_整合Mybatis
    Oracle AWR内容详解 参考学习钱若梨花落
    查看Oracle某时刻的客户端IP连接情况 参考学习钱若梨花落
    oracle Logminer 日志挖掘 参考学习钱若离花落
    静默升级oracle 11g (从11.2.0.1升级到11.2.0.4)
    oracle RAC集群启动和关闭
    856. Score of Parentheses
  • 原文地址:https://www.cnblogs.com/ZaraNet/p/9547581.html
Copyright © 2020-2023  润新知