ASP.NET MVC从数据库读取、存入图片
ASP.NET MVC从数据库读取、存入图片
一、DEMO效果
先选择图片,点击上传后,即可在照片预览中看到照片。如果需要更改,重新上传就可覆盖原图片。
二、代码
页面端,这里有个细节:再次上传后,如果<img>的URL不变,浏览器会从缓存中读取图片,这就会导致图片预览不会刷新,不显示刚上传的图片。解决这个问题只需要 传一个随机字符串作为参数即可。
@{
Layout = "~/Views/Shared/_LayoutPage1.cshtml";
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>图片编辑</title>
<link href="~/Scripts/bootstrap-datetimepicker/css/bootstrap-datetimepicker.min.css" rel="stylesheet" />
<link href="~/Scripts/toastr/build/toastr.min.css" rel="stylesheet" />
<script src="~/Scripts/bootstrap-datetimepicker/js/bootstrap-datetimepicker.min.js"></script>
<script src="~/Scripts/bootstrap-datetimepicker/js/locales/bootstrap-datetimepicker.zh-CN.js"></script>
<script src="~/Scripts/this/customEditor_fieldTypes.js"></script>
<script src="~/Scripts/this/tools.js"></script>
<script src="~/Scripts/toastr/build/toastr.min.js"></script>
</head>
<body>
<div class="row">
<div class="col-md-12">
<ul class="nav nav-tabs" id="myTab" style="margin-top:20px">
<li class="active"><a href="#tab_1" data-toggle="tab" class="btn" id="tabone">图片信息</a></li>
</ul>
<div class="tab-pane fade active in" id="tab_1">
<div class="form-group col-md-6">
@using (Ajax.BeginForm("", null, new AjaxOptions() { OnSuccess = "PostSuc", OnFailure = "PostFail", HttpMethod = "Post" }, new { enctype = "multipart/form-data", id = "FormImg" }))
{
<input type="hidden" name="EmployeeId" id="EmployeeId">
<span class="btn btn-default fileinput-button">
<input type="file" name="file1" id="file1">
</span>
<button class="btn btn-primary start" type="button" id="btnpictureid">
<span>
<i class="fa fa-file"></i> 上传
</span>
</button>
<fieldset>
<legend>照片预览</legend>
<img id="headimg" src="@Url.Action("ShowImage","Basic",new { @ViewBag.EmployeeId})" />
</fieldset>
}
</div>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
var EmployeeId = @ViewBag.EmployeeId;
$(document).ready(function () {
$("#EmployeeId").val(EmployeeId);
$("#btnpictureid").bind("click", function () { SaveImg(); });
})
function SaveImg() {
$("#FormImg").attr("data-ajax-success", "OnSaveImgSuccess(data)");
$("#FormImg").attr("data-ajax-failure", "OnSaveImgFail()");
$("#FormImg").attr("action", "/Basic/UploadImg");
$("#FormImg").submit();
}
function OnSaveImgSuccess(data) {
if (data.result == "success") {
toastr.success("上传成功");
$("#headimg").attr({ "src": "/Basic/ShowImage?EmployeeId=" + @ViewBag.EmployeeId +"&Random=" + (Math.random()*100)+1});//解决因为URL没变导致图片不刷新的问题
}
else {
toastr.error(data.msg);
}
}
function OnSaveImgFail(msg) {
toastr.error("图片上传失败,请重试!");
}
</script>
三、控制器端代码
///显示图片
public ActionResult ShowImage(long EmployeeId,int Random = 999 )
{
byte[] byData = _IEmployeeInfo.GetEmployeeById(EmployeeId).Image;
return File(byData, @"image/jpeg");
}
///上传图片
public ActionResult UploadImg(long EmployeeId)
{
string msg = string.Empty;
string result = string.Empty;
byte[] imgData = null;
int flag = 0;
if (Request.Files.Count > 0)
{
HttpPostedFileBase file = Request.Files["file1"];
if (file.ContentLength < 100 * 1024)
{
string fileType = System.IO.Path.GetExtension(file.FileName);//获取文件类型
if (fileType != null)
{
fileType = fileType.ToLower();//将文件类型转化成小写
if ("(.gif)|(.jpg)|(.bmp)|(.jpeg)|(.png)".Contains(fileType))
{
imgData = new byte[file.ContentLength];//新建一个长度等于图片大小的二进制地址
file.InputStream.Read(imgData, 0, file.ContentLength);//将image读取到ImageData中
flag = _IEmployeeInfo.UpdateImg(EmployeeId, imgData);
if (flag > 0)
{
result = Tips.success;
}
}
else
{
msg = "只支持图片格式";
result = Tips.fail;
}
}
}
else
{
msg = "图片大小不能超过100KB";
result = Tips.fail;
}
}
else
{
msg = "上传图片不能为空";
result = Tips.fail;
}
return Json(new Res { result = result, msg = msg });
}