ASP.NET--图片上传通过二进制保存到数据库
ASP.NET–图片上传通过二进制保存到数据库
开发工具:Visual Studio 2015、SQL Server 2014 Management Studio
关键技术:C# MVC
作者:刘东标
撰写时间:2019年1月18日
实现效果:
、、、、、、、、、、、、、html代码、、、、、、
@*选择文件*@
<div class="Education_two hide">
<span>学历信息</span>
<form action="/MyAccount/MyAccount/UpdateEducation" method="post" id="formSelectExaminee">
<input type="hidden" name="ClientID" value=" " />
<input type="hidden" name="EducationID" value=" " />
<div class="col-md-12 col-sm-12" style="margin-left:100px;">
<img src="" alt="" width="150" height="180" id="IimgStudentPicture" />
<input type="file" name="fileStudentImage" style="width:72px;height:22px;border:none;" id="IStudentPicture" />
<span>未选择任何文件</span>
</div>
<div class="col-md-12 col-sm-12">
<label>用户名:</label>
<input type="text" name="UserName" value="@Session["UserName"]" class="disn" readonly />
</div>
<div class="col-md-12 col-sm-12">
<label>真实姓名:</label>
<input type="text" name="TrueClientName" class="disn" readonly />
</div>
<div class="col-md-12 col-sm-12">
<label>毕业院校:</label>
<input type="text" name="School" />
</div>
<div class="col-md-12 col-sm-12">
<label>专业:</label>
<input type="text" name="Specialty" />
</div>
<div class="col-md-12 col-sm-12">
<label>学历:</label>
<input type="text" name="EducationBackground" />
</div>
<div class="col-md-12 col-sm-12">
<label>入学时间:</label>
<input type="date" name="EntranceDate" id="EntranceDate" />
</div>
<div class="col-md-12 col-sm-12">
<label>毕业年份:</label>
<input type="date" name="GraduateDate" id="GraduateDate" />
</div>
<div class="form-group" style="margin-left:100px;">
<button id="Reset" type="reset" class="btn btn-primary">重置</button>
<button id="SubmitOne" type="button" class="btn btn-primary">确定</button>
<button id="goHome1" type="button" class="btn btn-danger">关闭</button>
</div>
</form>
</div>
、、、、、、、、、、、、、js代码、、、、、、、、、、、、
//学历认证--新增
$("#SubmitOne").click(function () {
var School = $("#formSelectExaminee input[name='School']").val();
var Specialty = $("#formSelectExaminee input[name='Specialty']").val();
var EducationBackground = $("#formSelectExaminee input[name='EducationBackground']").val();
var EntranceDate = $("#formSelectExaminee input[name='EntranceDate']").val();
var EntranceDate = $("#formSelectExaminee input[name='EntranceDate']").val();
var Picture = $('#formSelectExaminee [name="fileStudentImage"]').prop('files');//照片
//判断一些必填项的数据是否为空
if (School != "" && Specialty != ""
&& EducationBackground != "" && EntranceDate != ""
&& EntranceDate != '') {
//显示 加载层(是第三方对话框的属性)
var layerIndex = layer.load(0);
//ajaxSubmit()提交表单:我们直接通过form提交的话, 提交后当前页面跳转到form的action所指向的页面。
//然而,很多时候我们并不希望提交表单后页面跳转,那么,我们就可以使用ajaxSubmit(obj)来提交数据
//ajaxSubmit(obj)方法是jQuery的一个插件jquery.form.js里面的方法,所以使用此方法需要先引入这个插件
$("#formSelectExaminee").ajaxSubmit(function (msg) {
layer.close(layerIndex);//关闭加载层
layer.alert(msg, { icon: 6, title: '提示' });
//重置表单
$('#formSelectExaminee [type="reset"]').click();
});
}
else {
layer.alert('请填写完整', { icon: 0, title: '提示' });
}
})
//FileReader接口提供了一个异步的API,通过这个API可以从浏览器中异步访问文件系统中的数据。因此,FileReader接口可以读取文件中的数据,并将读取的数据放入到内存中去
//选择照片:用FileReader对象来读取本地数据,并且将数据结果赋值给image的src、
//图片文件 正则表达式过滤
var imgReaderI = new FileReader();//FileReader()接口:用于读取文件
//图片文件: 正则表达式过滤(此表达式是用来判断上传的文件是否是一张图片)
regexImageFilter = /^(?:image\/bmp|image\/png|image\/jpeg|image\/jpg)$/i;
//调用FileReader接口的onload方法,回调函数得到的evt是图片的URL链接
imgReaderI.onload = function (evt) {
//将数据结果赋值给image的src
$("#IimgStudentPicture").attr('src', evt.target.result);
}
//获取“选择文件”的按钮,调用改变事件
$("#IStudentPicture").change(function () {
//获取通过“选择文件”的按钮上传的文件
//prop添加属性名称(跟attr属性一样是给标签添加属性,但是它们是有区别的),加载image标签中
var imgfFile = $("#IStudentPicture").prop('files')[0];
//调用正则表达式过滤图片
if (!regexImageFilter.test(imgfFile.type)) {
layer.msg('选择的不是一个有效的图片文件', { icon: 0 });
} //readAsDataURL()方法可以获取API异步读取的文件数据,另存为数据URL;将该URL绑定到img标签的src属性上,就可以实现图片的上传预览效果了。
imgReaderI.readAsDataURL(imgfFile);
})
、、、、、、、、、、、controller控制器代码、、、、、、、
//学历认证--数据回填用户ID
public ActionResult SelectEducationInfo(int UserID)
{
try
{
var list = (from tbEducation in myModel.S_Education
join tbClient in myModel.S_Client on tbEducation.ClientID equals tbClient.ClientID
where tbClient.UserID == UserID
select new
{
ClientID = tbEducation.ClientID,
EducationID = tbEducation.EducationID,
TrueClientName = tbClient.TrueClientName,
Picture = tbEducation.Picture,
}).ToList();
return Json(list, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
//学历认证
public ActionResult UpdateEducation(S_Education education, HttpPostedFileBase fileStudentImage)
{
string strMsg = "学历认证失败";
try
{
var list = (from tbEducation in myModel.S_Education
join tbClient in myModel.S_Client on tbEducation.ClientID equals tbClient.ClientID
where tbClient.ClientID == education.ClientID
select tbEducation).Single();
if (list.Picture != null)
{
strMsg = "已经认证,学历认证失败";
}
else
{
if (fileStudentImage != null && fileStudentImage.ContentLength > 0)
{
byte[] imgFile = null;//读取上传的图片
//判断是否上传图片(判断图片的值 && 判断图片的长度)
//有上传图片
imgFile = new byte[fileStudentImage.ContentLength];//初始化为图片的长度//读取该图片文件//将图片转为流结束位置
//将流读取为byte[],参数:byte[],读取开始位置,读取字节数
fileStudentImage.InputStream.Read(imgFile, 0, fileStudentImage.ContentLength);
education.Picture = imgFile;
}
list.EducationBackground = education.EducationBackground;
list.School = education.School;
list.Specialty = education.Specialty;
list.EntranceDate = education.EntranceDate;
list.GraduateDate = education.GraduateDate;
list.Picture = education.Picture;
myModel.Entry(list).State = System.Data.Entity.EntityState.Modified;
myModel.SaveChanges();
strMsg = "学历认证成功";
}
}
catch (Exception e)
{
throw;
}
return Json(strMsg, JsonRequestBehavior.AllowGet);
}
//根据studentId查询学历照片(学历ID)
public ActionResult GetStudentImage(int UserID)
{
try
{
var list = (from tbEducation in myModel.S_Education
join tbClient in myModel.S_Client on tbEducation.ClientID equals tbClient.ClientID
where tbClient.UserID == UserID
select new
{
tbEducation.Picture
}).Single();
byte[] imageData = list.Picture;
return File(imageData, @"image/jpg");
}
catch (Exception e)
{
Console.WriteLine(e);
return null;
}
}
//查看学历
public ActionResult SelectEducation(int UserID)
{
try
{
var list = (from tbEducation in myModel.S_Education
join tbClient in myModel.S_Client on tbEducation.ClientID equals tbClient.ClientID
where tbClient.UserID == UserID
select new
{
tbEducation.Specialty,
tbEducation.School,
GraduateDate = tbEducation.GraduateDate.ToString(),
EntranceDate = tbEducation.EntranceDate.ToString(),
tbEducation.EducationBackground,
tbClient.TrueClientName,
tbEducation.Picture,
}).Single();
return Json(list, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}