使用.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");
 }
相关推荐
Cyan_RA915 小时前
SpringMVC @RequestMapping的使用演示和细节 详解
java·开发语言·后端·spring·mvc·ssm·springmvc
csdn_aspnet2 天前
MongoDB C# .NetCore 驱动程序 序列化忽略属性
mongodb·c#·.netcore
Tiger_shl3 天前
【.Net技术栈梳理】08-控制反转(IoC)与依赖注入(DI)
开发语言·.net·.netcore
Tiger_shl3 天前
【.Net技术栈梳理】10-.NET Core 程序的执行
开发语言·.net·.netcore
MoFe14 天前
【.net core】【watercloud】登陆后跳转至指定页面,显示在系统框架页内
.netcore
周杰伦fans4 天前
.net core webapi/mvc阿里云服务器部署 - 错误解决
阿里云·mvc·.netcore
BFT白芙堂4 天前
GRASP 实验室研究 论文解读 | 机器人交互:基于神经网络引导变分推理的快速失配估计
人工智能·神经网络·机器学习·mvc·人机交互·科研教育机器人·具身智能平台
William_cl4 天前
MVC 中 AJAX 与前后端交互深度实战(含独家避坑与场景化方案)
ajax·mvc·交互
Cyan_RA95 天前
SpringMVC 执行流程分析 详解(图解SpringMVC执行流程)
java·人工智能·后端·spring·mvc·ssm·springmvc
hello 早上好5 天前
Spring MVC 类型转换与参数绑定:从架构到实战
spring·架构·mvc