因项目需求需要一个上传图片并显示的功能类似于上传头像并显示出来。查阅了网上资料写了个Demo希望能帮助到更多的人。此Demo基于ASP.NET MVC实现。
选择图片
点击按钮进行上传
一、先在项目中新建一个文件夹用于存放图片
二、View页面代码
{Layout null;}using (Ajax.BeginForm("", null, new AjaxOptions() { OnSuccess "PostSuc", OnFailure "PostFail", HttpMethod "Post" }, new { enctype "multipart/form-data", id "FormBaseData" })){}
三、Controller端代码
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;namespace WebApplication1.Controllers{public class HomeController : Controller{public ActionResult Index(){return View();}[HttpPost]public ActionResult UploadImg(long MouldId){string msg string.Empty;if (Request.Files.Count > 0){HttpPostedFileBase file Request.Files["file1"];if (file.ContentLength <5 * 1024 * 1024){string fileType System.IO.Path.GetExtension(file.FileName);//获取文件类型if (!System.IO.Directory.Exists(Server.MapPath("~/Pictures/"))){System.IO.Directory.CreateDirectory(Server.MapPath("~/Pictures/"));}string filePath Server.MapPath("~/Pictures/");//保存文件的路径if (fileType ! null){fileType fileType.ToLower();//将文件类型转化成小写if ("(.gif)|(.jpg)|(.bmp)|(.jpeg)|(.png)".Contains(fileType)){file.SaveAs(filePath file.FileName);string str "Pictures/" file.FileName;msg str;}else{msg "只支持图片格式";}}}else{msg "图片大小不能超过5M";}}else{msg "上传图片不能为空";}return Content(msg);}}}
参考https://blog.csdn.net/weixin_44540201/article/details/89630530