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

  • 相关阅读:
    delegate
    Event
    SQL:删除重复数据,只保留一条
    c#符号
    linux下vim命令详解【转】
    Probabilistic latent semantic analysis【转】
    Ubuntu下如何使用虚拟机安装WindowsXP?(2)【转】
    C文件操作fopen打开标记设置问题【学习笔记】
    Plate notation【转】
    最大似然估计(Maximum likelihood estimation) 【转】
  • 原文地址:https://www.cnblogs.com/ZaraNet/p/9547581.html
Copyright © 2011-2022 走看看