使用js插件和imput file实现上传图片,并显示预览图片功能。经常用在用户个人信息页面,用户选择个人证件照片—预览—上传—保存数据库。Codeby lanhai96
实现效果如下图:
页面右侧,用户点击“选择文件”,显示下图
选择自己的用户照片,在右侧的图片窗口就会显示用户选择图片的预览。
用户确定无误后,点击上传,此时图片根据规则已上传至服务器指定地址。
最后,用户修改其他信息,如姓名,修改完毕后:
点击保存,将实现修改的信息和修改的图片一起保存到数据库。
保存数据成功后,将刷新显示当前修改的信息。
以上功能使用bootstrap框架,支持除IE 8以下外的所有主流浏览器。
实现以上功能的核心代码如下:
1、引入关键的js和css文件
<script type="text/javascript" src="./Scripts/jquery-1.8.1.min.js"></script>
<script type="text/javascript" src="./Scripts/CJL.0.1.min.js"></script>
<script type="text/javascript" src="./Scripts/QuickUpload.js"></script>
<script type="text/javascript" src="./Scripts/jquery.form.js"></script>
其他样式文件略
2、body中的关键元素
<tr>
<td>
姓名:
</td>
<td>
<asp:HiddenField ID="hid_userid" runat="server" Value="" />
<input id="username" type="text" class="form-control" value='<%=username %>' />
</td>
<td>
电话:
</td>
<td>
<input id="telphone" type="text" class="form-control" value='<%=telphone %>' />
</td>
<td>
拼音:
</td>
<td>
<input type="text" class="form-control" value='<%=pinyin %>' />
</td>
<td rowspan="3" style="padding-left:15px;height:180px;width:150px;">
<div id="hidpic" style=" visibility:hidden;" runat="server"><%=photo %></div>
<div>
<img id="idImg" style="width:195px;height:240px;" title="照片"/>
</div>
<div style="margin:10px;float:left;">
<span id="filebtn" class="btn" >选择文件:</span>
<div style="height:20px;width:50px;border-radius:4px;background-color:green;visibility:hidden;">
<input id="idFile" runat="server" name="pic" type="file" />
</div>
</div>
<div style="margin-top: 10px;">
<input type="button" name="resets" value="上传" class="btn" onclick="upLoadFile()" />
</div>
</td>
</tr>
3、前台关键的函数和方法
图片通过ajax方法上传,上传后通过js插件来显示预览
function clearFileInput() {
var form = document.createElement('form1');
document.body.appendChild(form);
//记住file在旧表单中的的位置
var file = document.getElementById("idFile");
var pos = file.nextSibling;
form.appendChild(file);
form.reset();//ͨ重置form下的窗口
document.getElementById("colspan").appendChild(file);
document.body.removeChild(form);
//获取图片元素对象
document.getElementById("idImg").style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='images/noimage.jpg'";
$("#idImg").attr('src', 'images/noimage.jpg');
$("#idImg").removeAttr('src');
$("#idImg").removeAttr('style');
}
function upLoadFile() {
$('#form1').ajaxSubmit({
semantic: true,
type: 'post',
url: './userphotofile.ashx',//调用后台程序上传图片到指定位置
success: function (result) {
if (result == "false") {
alert("失败");
}
else {
$('#hidpic').html(result);//上传成功后,记录图片路径
alert("成功");
}
},
error: function (result) {
alert("失败" + result);
}
});
}
$(document).ready(function () {
$('#filebtn').click(function () {
$('#idFile').click();
});
});
以下的图片预览的js要放到页面的最后:
<script type="text/javascript" src="./Scripts/ImagePreview.js"></script>
<script type="text/javascript">
var ip = new ImagePreview($$("idFile"), $$("idImg"), {
maxWidth: 200, maxHeight: 200, action: "./ImagePreview.ashx"
});
ip.img.src = ImagePreview.TRANSPARENT;
ip.file.onchange = function () { ip.preview(); };
</script>
文件修改完成后,同样使用ajax方式,实现所有数据的最终保存。
$('#save').click(function () {
var name = $('#username').val();
var userid = $('#hid_userid').val();
var telphone = $('#telphone').val();
var hidpicpath = $('#hidpic').html();
var userjson;
userjson = {
UserID: userid,
UserName: name,
Usertelephone: telphone,
UserPhoto: hidpicpath
};
var tr_data = JSON.stringify(userjson);
$.ajax({
contentType: "application/json",
type: "post",
datatype: "json",
url: "index.aspx/Save",
data: "{'data':'" + tr_data + "'}",
success: function (msg) {
alert("保存成功");
window.location.href = "index.aspx";
},
error: function (x) {
alert("失败" + x);
window.location.href = "index.aspx";
}
});
});
4、后台代码部分
//页面加载时,初始化的数据
protected void InitData(string userid)
{
Users user = new Users();
DataTable dt = DBHelp.GetDataSet("select * from Users");
username = dt.Rows[0]["UserName"].ToString() ;
pinyin = dt.Rows[0]["UserPinYin"].ToString();
if (dt.Rows[0]["UserPhoto"].ToString() != null || dt.Rows[0]["UserPhoto"].ToString() != "./image/noimage.jpg" || dt.Rows[0]["UserPhoto"].ToString() != "")
{
photo = dt.Rows[0]["UserPhoto"].ToString();
}
else
user.UserPhoto = "./image/noimage.jpg";
if (dt.Rows[0]["telephone"].ToString() != null || dt.Rows[0]["telephone"].ToString() != "")
{
telphone = dt.Rows[0]["telephone"].ToString();
}
else
{
telphone = "";
}
}
//ajax调用后台时的方法
[WebMethod]
public static bool Save(string data)
{
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
Users _jsondutydata = jsonSerializer.Deserialize<Users>(data);
Users user = new Users();
user.UserID = _jsondutydata.UserID;
user.UserName = _jsondutydata.UserName;
user.Usertelephone = _jsondutydata.Usertelephone;
user.UserPhoto = _jsondutydata.UserPhoto;
string sql = "Update Users Set UserName=@Username,UserPhoto=@UserPhoto,telephone=@userphone where UserID='" + user.UserID + "'";
SqlParameter[] para = new SqlParameter[]
{
new SqlParameter("@Username",user.UserName),
new SqlParameter("@UserPhoto",user.UserPhoto),
new SqlParameter("@userphone",user.Usertelephone)
};
int i = DBHelp.ExecuteCommand(sql, para);
if (i > 0)
{
return true;
}
else
{
return false;
}
}
5、两个处理程序的代码
Userphotofile.ashx
//用户图片上传
public class userphotofile : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
// context.Response.ContentType = "text/plain";
string res = "";
HttpFileCollection files = context.Request.Files;
if (files.Count > 0)
{
Random rnd = new Random();
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
if (file.ContentLength > 0)
{
string fileName = file.FileName;
string extension = Path.GetExtension(fileName);
int num = rnd.Next(5000, 10000);
string path = "./photo/" + num.ToString() + extension;
file.SaveAs(System.Web.HttpContext.Current.Server.MapPath(path));
res = path.Substring(1, path.Length - 1);
//更新该用户数据库
}
}
context.Response.Write(res);
}
else
{
context.Response.Write("false");
}
}
ImagePreview.ashx
//图片预览处理程序
public void ProcessRequest(HttpContext context)
{
if (context.Request.Files.Count > 0)
{
HttpPostedFile file = context.Request.Files[0];
if (file.ContentLength > 0 && file.ContentType.IndexOf("image/") >= 0)
{
int width = Convert.ToInt32(context.Request.Form["width"]);
int height = Convert.ToInt32(context.Request.Form["height"]);
string path = "data:image/jpeg;base64," + Convert.ToBase64String(ResizeImg(file.InputStream, width, height).GetBuffer());
context.Response.Write(path);
}
}
}
public MemoryStream ResizeImg(Stream ImgFile, int maxWidth, int maxHeight)
{
Image imgPhoto = Image.FromStream(ImgFile);
decimal desiredRatio = Math.Min((decimal)maxWidth / imgPhoto.Width, (decimal)maxHeight / imgPhoto.Height);
int iWidth = (int)(imgPhoto.Width * desiredRatio);
int iHeight = (int)(imgPhoto.Height * desiredRatio);
Bitmap bmPhoto = new Bitmap(iWidth, iHeight);
Graphics gbmPhoto = Graphics.FromImage(bmPhoto);
gbmPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, iWidth, iHeight), new Rectangle(0, 0, imgPhoto.Width, imgPhoto.Height), GraphicsUnit.Pixel);
MemoryStream ms = new MemoryStream();
bmPhoto.Save(ms, ImageFormat.Jpeg);
imgPhoto.Dispose();
gbmPhoto.Dispose();
bmPhoto.Dispose();
return ms;
}
数据库操作的代码这里省略了,详细功能可以参考源码。源码和数据库下载地址:https://download.csdn.net/download/lanhai96/86398822
几个注意事项:
1、js中调用的form1,是form的id;
2、form中要配置enctype参数,不然不能传递对象。
<form id="form1" runat="server" method="post" enctype="multipart/form-data">
3、使用ajaxSubmit要引用jquery.form.js,同时配置semantic参数为true,才能支持极速360等主流浏览器,不然只支持firefox浏览器。
$('#form1').ajaxSubmit({
semantic: true,
4、注意留心JSON对象的创建和解析。
5、[WebMethod]的用法:带有这个标识的方法,可以在在前端直接利用ajax方法调用
6、文章全为原创,码字不易,转载请注明蓝海云梦。