使用.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");
 }
相关推荐
MoFe112 小时前
【.net core】【watercloud】树形组件combotree导入及调用
.netcore
MoFe112 小时前
【.net core】.KMZ文件解压为.KML文件并解析为GEOJSON坐标数据集。附KML处理多线(LineString)闭环问题
.netcore
The Future is mine1 天前
在.NET Core控制器中获取AJAX传递的Body参数
c#·.netcore
无味无感1 天前
ASP.NET Core使用Quartz部署到IIS资源自动被回收解决方案
.netcore
MoFe11 天前
【.net core】天地图坐标转换为高德地图坐标(WGS84 坐标转 GCJ02 坐标)
java·前端·.netcore
面朝大海,春不暖,花不开2 天前
Spring Boot MVC自动配置与Web应用开发详解
前端·spring boot·mvc
步、步、为营3 天前
.NET Core接口IServiceProvider
.net·.netcore
残*影4 天前
什么是MVC?
java·spring·mvc
保持学习ing4 天前
黑马Java面试笔记之框架篇(Spring、SpringMvc、Springboot)
java·笔记·spring·面试·mvc·mybatis·springboot
超级无敌永恒暴龙战士4 天前
SpringBoot-配置Spring MVC
spring boot·spring·mvc