使用.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");
 }
相关推荐
Lost of 程序猿6 小时前
ASP.NET Core 后台任务全景:从 BackgroundService 到 Channel 队列,再到分布式调度
后端·asp.net·.netcore
宝桥南山1 天前
Blazor Web Assembly - 体验一下Authentication State从Server共享给Client
microsoft·微软·c#·asp.net·.net·.netcore
小小龙学IT4 天前
Qt 模型/视图框架(Model/View)深度解析:从 MVC 演化到数据展示架构的王者
qt·架构·mvc
树码小子5 天前
什么是大语言模型
人工智能·语言模型·mvc
evans在进步5 天前
Spring MVC 核心机制详解:全局异常处理、请求跳转与数据绑定
java·spring·mvc
小林ixn6 天前
NestJS 入门实战:从 0 到 1 撸一个 Todo CRUD,感受装饰器与模块化的优雅
后端·mvc·nestjs
breeze jiang6 天前
NestJS MVC 实战:用 hello 项目 7 个文件讲清分层、装饰器、依赖注入与错误处理
node.js·mvc·js
爱敲键盘的猴子7 天前
Spring MVC 详解(一):全注解开发与请求响应处理
java·spring·mvc
宝桥南山11 天前
Microsoft Agent Framework(.NET) - 尝试一下从MCP Server上获取Agent Skills
ai·微软·c#·aigc·.net·.netcore
醇氧15 天前
MVC、MVP、MVVM 架构详解、分析与对比
架构·mvc