使用.net core MVC实现图片上传下载

今天闲来无事,复习复习

1、上传

上传界面

html 复制代码
<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="UpImage" class="form">
        <div class="form-group">
            <input type="file" name="formFile" />
            <input type="submit" value="上传" class="btn btn-default" />
        </div>
    </form>
</div>

上传的后台

cs 复制代码
  //文件上传
  [HttpPost]
  public IActionResult UpImage(IFormFile formFile)//参数名一定要与前端保持一致
  {
      var ex = Path.GetExtension(formFile.FileName);
      var newFilename = Path.Combine(_webHostEnvironment.WebRootPath, "temp", Guid.NewGuid().ToString().ToUpper().Replace("-", "") + ex);
      using (FileStream fs = new FileStream(newFilename, FileMode.OpenOrCreate, FileAccess.Write))
      {
          formFile.CopyTo(fs);
      }
      return Ok("Privacy");
  }

2、下载

进下载页面前

cs 复制代码
public IActionResult Privacy()
{
    var wr = _webHostEnvironment.WebRootPath;
    var fullPath = Path.Combine(wr, "temp");
    var oldfiles = Directory.GetFiles(fullPath);
    var newfile = new string[oldfiles.Length];
    for (int i = 0; i < oldfiles.Length; i++)
    {
        newfile[i] = oldfiles[i].Replace(wr, "").Replace("//", "/").Replace("\\", "/");
    }
    return View("Privacy", newfile);
}

下载页的前端

html 复制代码
@model string[]
<h1>MVC文件上传下载</h1>

<div class="container">
    <div class="row">
        @for (int i = 0; i < Model.Length; i++)
        {
            <div class="col-sm-4">
                <img src="@Model[i]" class="img-fluid" style="margin-bottom:10px;">
                <a class="btn btn-primary btn-lg" asp-controller="Home" asp-action="DownImage" asp-route-filePath="@Model[i]">
                    下 载
                </a>
            </div>
        }
    </div>
</div>

下载页的后端

cs 复制代码
 //文件下载
 public IActionResult DownImage(string filePath)
 {
     string contentType = "image/jpeg";
     var path = _webHostEnvironment.WebRootPath + filePath;
     FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
     return File(fileStream, contentType, DateTime.Now.ToString("F") + ".jpg");
 }
相关推荐
又是忙碌的一天5 小时前
SpringMVC的处理流程
java·mvc
派大鑫wink7 小时前
【Day37】MVC 设计模式:原理与手动实现简易 MVC 框架
java·设计模式·mvc
卓怡学长9 小时前
m111基于MVC的舞蹈网站的设计与实现
java·前端·数据库·spring boot·spring·mvc
码界奇点2 天前
基于Spring MVC的缺陷管理系统设计与实现
java·spring·车载系统·毕业设计·mvc·源代码管理
weixin_421994782 天前
认识数据 - 变量与数据类型
c#·.net·.netcore
工业甲酰苯胺2 天前
如何一步步将 ASP.NET MVC 升级为.NET
asp.net·mvc·.net
老龄程序员2 天前
记一次由于.netcore程序堆栈溢出的问题分析
.netcore
雪人.2 天前
Spring MVC经典面试
java·spring·mvc
一然明月3 天前
.NET Core基础
.netcore
我来整一篇4 天前
[Razor] ASP.NET Core MVC 前端组件快速使用总结
前端·asp.net·mvc