使用.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");
 }
相关推荐
zzb158012 天前
ios基础-MVC-UIView
ios·mvc·cocoa
秋雨梧桐叶落莳14 天前
iOS——QQ音乐仿写项目总结
学习·macos·ui·ios·mvc·objective-c·xcode
mikasa66715 天前
关于Spring MVC 基于 AOP 实现的全局控制器统一处理方案@ControllerAdvice
java·spring·mvc
仍然.15 天前
Spring MVC(2)--- 介绍响应数据,具体案例和三层架构
mvc
仍然.16 天前
Spring MVC(1)---介绍Spring MVC 和 请求数据
java·spring·mvc
摇滚侠17 天前
Spring MVC 不是一个单独的框架,是 Spring 框架的一个模块
java·spring·mvc
我登哥MVP19 天前
Spring Boot 从“会用”到“精通”:SpringBoot MVC 请求处理全流程
java·spring boot·后端·spring·mvc·maven·intellij-idea
摇滚侠20 天前
JavaWeb 全套教程 MVC 模式 93
mvc
代码的小搬运工21 天前
【iOS】MVC架构
ios·架构·mvc
qq_25183645722 天前
基于MVC的学校食堂点餐管理系统的设计与实现
mvc