因项目需求,需要一个上传图片并显示的功能,类似于上传头像并显示出来。查阅了网上资料,写了个Demo,希望能帮助到更多的人。此Demo基于ASP.NET MVC实现。
选择图片:
点击按钮进行上传:
一、先在项目中新建一个文件夹用于存放图片
二、View页面代码
@{Layout = null;
}<!DOCTYPE html>
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0"><script src="~/Scripts/jquery-3.3.1.min.js"></script><script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
</head>
<body>@using (Ajax.BeginForm("", null, new AjaxOptions() { OnSuccess = "PostSuc", OnFailure = "PostFail", HttpMethod = "Post" }, new { enctype = "multipart/form-data", id = "FormBaseData" })){<input type="hidden" name="MouldId" id="MouldId" value="9527" /><input type="file" name="file1" /><input type="button" value="submit" id="btnSubmit" /><img src="" width="300" height="300" display:inline; alt="图片预览" id="mypicture" />}
</body>
</html><script type="text/javascript">$(document).ready(function () {$("#btnSubmit").bind("click", function () { Query(); });})function Query() {$("#FormBaseData").attr("data-ajax-success", "OnQuerySuccess(data)");$("#FormBaseData").attr("data-ajax-failure", "OnQueryFail()");$("#FormBaseData").attr("action", "/home/UploadImg");$("#FormBaseData").submit();}function OnQuerySuccess(data) {$("#mypicture").attr({ "src": data });}function OnQueryFail() {alert("发生错误!");}
</script>
三、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