文件上传

  • 一、控制器
  • 二、Model
    • 1.类
    • 2.视图
  • 总结

一、控制器

 [HttpPost]public IActionResult Edit(StudentEditViewModel model){//检查提供的数据是否有效,如果没有通过验证,需要重新编辑学生信息// 这样用户就可以更正并重新提交编辑表单if (ModelState.IsValid){Student student = _studentRepository.GetStudent(model.Id);student.Email = model.Email;student.Name = model.Name;student.ClassName = model.ClassName;if (model.Photos.Count > 0){if (model.ExistingPhotoPath != null){string filePath = Path.Combine(webHostEnvironment.WebRootPath, "images", model.ExistingPhotoPath);System.IO.File.Delete(filePath);}student.PhotoPath = ProcessUploadedFile(model);}Student updateStudent = _studentRepository.Update(student);return RedirectToAction("Index");}return View();}/// <summary>/// 将照片保存到指定的路径中,并返回唯一的文件名/// </summary>/// <returns></returns>private string ProcessUploadedFile(StudentCreateViewModel model){string uniqueFileName = null;if (model.Photos.Count > 0){foreach (var photo in model.Photos){//必须将图像上传到wwwwroot中的images文件夹//而要获取wwwroot文件夹的路径,我们需要注入ASP.NET Core提供的IWebHostEnvironment//通过IWebHostEnvironment服务去获取wwwroot文件夹的路径string unloadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "images");// 为了确保文件名是唯一的,我们在文件名后附加一个新的GUID值和一个下划线uniqueFileName = Guid.NewGuid().ToString() + "_" + photo.FileName;//路径string filePath = Path.Combine(unloadsFolder, uniqueFileName);//因为使用了非托管资源,所以需要手动进行释放using (var fileStream = new FileStream(filePath, FileMode.Create)){//复制到指定位置photo.CopyTo(fileStream);}}}return uniqueFileName;}

二、Model

1.类

代码如下(示例):

 public class StudentEditViewModel:StudentCreateViewModel{public int Id { get; set; }public string ExistingPhotoPath { get; set; }}public class StudentCreateViewModel{[Display(Name = "名字")][Required(ErrorMessage = "请输入名字"), MaxLength(50, ErrorMessage = "名字的长度不能超过50个字符")]public string Name { get; set; }[Required][Display(Name = "班级信息")]public ClassNameEnum? ClassName { get; set; }[Required(ErrorMessage = "请输入邮箱地址")][Display(Name = "邮箱地址")][RegularExpression(@"^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$",ErrorMessage = "邮箱的格式不正确")]public string Email { get; set; }[Display(Name="图片")]public List<IFormFile> Photos { get; set; }}

2.视图

代码如下(示例):

@model StudentEditViewModel
@{ViewBag.Title = "编辑学生信息";//获取当前学生照片信息路径var photoPath = "~/images/" + (Model.ExistingPhotoPath ?? "1.jpg");
}<form enctype="multipart/form-data" asp-controller="home" asp-action="edit" method="post" class="mt-3"><div asp-validation-summary="All" class="text-danger"></div><input hidden asp-for="Id" /><input hidden asp-for="ExistingPhotoPath" /><div class="form-group row"><label asp-for="Name" class="col-sm-2 col-form-label"></label><div class="col-sm-10"><input asp-for="Name" class="form-control" placeholder="请输入名字" /><span asp-validation-for="Name" class="text-danger"></span></div></div><div class="form-group row"><label asp-for="Email" class="col-sm-2 col-form-label"></label><div class="col-sm-10"><input asp-for="Email" class="form-control" placeholder="请输入邮箱" /><span asp-validation-for="Email" class="text-danger"></span></div></div><div class="form-group row"><label asp-for="ClassName" class="col-sm-2 col-form-label"></label><div class="col-sm-10"><select asp-for="ClassName" asp-items="Html.GetEnumSelectList<ClassNameEnum>()" class="custom-select mr-sm-2"><option value="">请选择</option></select><span asp-validation-for="ClassName" class="text-danger"></span></div></div><div class="form-group row"><label asp-for="Photos" class="col-sm-2 col-form-label"></label><div class="col-sm-10"><div class="custom-file"><input asp-for="Photos" multiple class="form-control custom-file-input" /><label class="custom-file-label">请选择照片......</label></div></div></div> <div class="form-group row col-sm-4 offset-4"><img class="imagesThumbnail" src="@photoPath" asp-append-version="true" /></div><div class="form-group row"><div class="col-sm-10"><button type="submit" class="btn btn-primary">更新</button><a asp-action="index" asp-controller="home" class="btn btn-primary">取消</a></div></div>    @section Scripts{<script type="text/javascript">$(document).ready(function () {$('.custom-file-input').on("change", function () {console.log($(this))//var fileName = $(this).val().split("\\").pop();//$(this).next(".custom-file-label").html(fileName);var fileLable = $(this).next(".custom-file-label");var files = $(this)[0].files;if (files.length > 1) {fileLable.html("您已经选择了" + files.length + "个文件");} else {fileLable.html(files[0].name);}});})</script>}
</form>

总结

HttpGet没有写出来,多张图片上传

Asp Net Core普通图片上传相关推荐

  1. .net core 7图片上传到数据库和浏览

    项目场景: .net core 7 图片上传 本来以为前面有asp的理解这块应该不成问题,但还是花费了两天时间,期间看了下官方的文档(官方文档core上传)才解决 1.这是我的模型 2.控制器 pub ...

  2. .net core api 图片上传与加载

    关于.net core API 图片上传与加载 文件夹 [TOC] 1.上传图片 1.配置Swagger 与文件夹.接口添加 1.建立.net core api 项目 下载 NuGet 包 Swash ...

  3. asp.net mvc 上传到服务器 图片不显示,ASP.NET MVC实现图片上传、图片预览显示

    先看看效果(下面gif动画制作有点大,5.71MB): 题外话:上面选择图片来源于Insus.NET的新浪微博,言归正传,由于以前的asp.net mvc的练习文件上传文件,显示或是下载等博文,均是存 ...

  4. Vue + Element+ ASP.NET Core WebAPI 文件上传下载

    以ASP.NET Core WebAPI 作后端 API ,用 Vue 构建前端页面,用 Axios 从前端访问后端 API ,包括文件的上传和下载. 准备asp.net后端文件上传的API Uplo ...

  5. vue+element-ui+asp.net core 实现文件上传和下载

    原文连接 个人心得: 1.前端需要发送http请求到后端 2.后端用接受到请求之后,返回一个FileContentResult类型,提醒浏览器下载

  6. Asp.Net Core Web Api图片上传及MongoDB存储实例教程(一)

    图片或者文件上传相信大家在开发中应该都会用到吧,有的时候还要对图片生成缩略图.那么如何在Asp.Net Core Web Api实现图片上传存储以及生成缩略图呢?今天我就使用MongoDB作为图片存储 ...

  7. Asp.Net Core Web Api图片上传(一)集成MongoDB存储实例教程

    Asp.Net Core Web Api图片上传(一)集成MongoDB存储实例教程 原文:Asp.Net Core Web Api图片上传(一)集成MongoDB存储实例教程 Asp.Net Cor ...

  8. php图片上传为base64,php实现base64图片上传方式实例代码

    /** * base64图片上传 * @param $base64_img * @return array */ header("content-type:text/html;charset ...

  9. ASP.NET Core 简单实现七牛图片上传(FormData 和 Base64)

    ASP.NET Core 简单实现七牛图片上传(FormData 和 Base64) 七牛图片上传 SDK(.NET 版本):https://developer.qiniu.com/kodo/sdk/ ...

最新文章

  1. Java项目:星际争霸游戏(java+swing+awt界面编程+IO输入输出流+socket+udp网络通信)
  2. 使用cacti对mysql监控的图像解释_Linux下的监控软件cacti的安装与配置
  3. TOYS-POJ2318
  4. 在windows下python,pip,numpy,scipy,matplotlib的安装
  5. 2019.7.20js基础知识整理
  6. Python 连续三年夺冠、PHP 受排挤,揭晓 IEEE Spectrum 2019 年度编程语言排行榜
  7. shell批量文件编码转换
  8. Flash游戏开发技术分析(下)
  9. 企业运维,至少包括如下几个大方面: 1,桌面运维(以windows为主,工资偏低,桌面运维经理可以达到8K到10K,很多人在公司里干的就是安装windows系统,windows里的QQ坏了重装下,砸个
  10. 腾讯推出微信企业服务平台风铃
  11. 智能云防雷,信号浪涌保护器防雷接地方案
  12. 怎么用计算机录像,怎么用电脑自带屏幕录制工具?免费录制方法
  13. 如何选择北京市医疗定点机构---初级班
  14. 零基础移动端APP设计与开发教程
  15. webshell提权宝典
  16. 年会抽奖源码html js,js年会抽奖程序
  17. USB HUB芯片 FE8.1替代方案
  18. 网络安全笔记第三天day3(kali2021系统的安装)
  19. php mdx,多维建模和MDX中出现的一些概念
  20. 电机 输送机 机械手 提升机 发酵罐 减速机 破碎机

热门文章

  1. Amberantechamber | 创建小分子力场参数文件
  2. 关于SIP防火墙穿越的汇总 .
  3. 浏览器的进程,线程,事件轮询机制
  4. Ubuntu安装nginx并部署静态网站
  5. 杨辉三角,这个三角不太样
  6. Ichunqiu云境 —— Exchange Writeup
  7. Oracle安装后的默认账号以及一些基本操作
  8. 【雷达系统导论】-雷达方程
  9. h5的二维三维动画杂谈
  10. android studio aapt err,Android Studio 3.0,AAPT2编译失败 – 资源文件中的dimen无效