完成修改头像功能,用户表中增加了头像字段

This commit is contained in:
lq_avenue 2016-11-15 11:15:38 +08:00
parent 2c4e82f699
commit 5293695f33
12 changed files with 407 additions and 26 deletions

View File

@ -132,6 +132,7 @@
<Content Include="Content\images\logo4.jpg" />
<Content Include="Content\images\logo5.jpg" />
<Content Include="Content\images\logo6.jpg" />
<Content Include="Content\js\ajaxfileupload.js" />
<Content Include="Content\js\bootstrap-datetimepicker.js" />
<Content Include="Content\js\bootstrap-select.js" />
<Content Include="Content\js\bootstrap-select.min.js" />
@ -188,6 +189,7 @@
<Content Include="Scripts\Exceptions.js" />
<Content Include="Scripts\Groups.js" />
<Content Include="Scripts\icon.js" />
<Content Include="Scripts\Infos.js" />
<Content Include="Scripts\lock.js" />
<Content Include="Scripts\Login.js" />
<Content Include="Scripts\Logs.js" />
@ -212,7 +214,9 @@
<Content Include="Content\js\framework.js" />
<Content Include="Scripts\well.js" />
<Content Include="Views\Shared\Readme.txt" />
<Content Include="Web.config" />
<Content Include="Web.config">
<SubType>Designer</SubType>
</Content>
<Content Include="Views\Shared\_Layout.cshtml" />
<Content Include="Views\Home\Index.cshtml" />
</ItemGroup>
@ -230,6 +234,7 @@
<Compile Include="Controllers\ExceptionsController.cs" />
<Compile Include="Controllers\GroupsController.cs" />
<Compile Include="Controllers\HomeController.cs" />
<Compile Include="Controllers\InfosController.cs" />
<Compile Include="Controllers\LogsController.cs" />
<Compile Include="Controllers\MenusController.cs" />
<Compile Include="Controllers\MessagesController.cs" />
@ -304,7 +309,10 @@
<DependentUpon>Web.config</DependentUpon>
</None>
</ItemGroup>
<ItemGroup />
<ItemGroup>
<Folder Include="Content\images\uploader\" />
<Folder Include="Views\Infos\" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Bootstrap.DataAccess\Bootstrap.DataAccess.csproj">
<Project>{af16ca71-b8c6-4f51-b38c-0c0300fdebd7}</Project>

View File

@ -0,0 +1,224 @@
// JavaScript Document
jQuery.extend({
createUploadIframe: function (id, uri) {
//create frame
var frameId = 'jUploadFrame' + id;
if (window.ActiveXObject) {
//var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
var io = document.createElement('IFRAME');
io.id = frameId;
io.name = frameId;
if (typeof uri == 'boolean') {
io.src = 'javascript:false';
}
else if (typeof uri == 'string') {
io.src = uri;
}
}
else {
var io = document.createElement('iframe');
io.id = frameId;
io.name = frameId;
}
io.style.position = 'absolute';
io.style.top = '-1000px';
io.style.left = '-1000px';
document.body.appendChild(io);
return io;
},
createUploadForm: function (id, fileElementId) {
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
//set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
return form;
},
ajaxFileUpload: function (s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = s.fileElementId;
var form = jQuery.createUploadForm(id, s.fileElementId);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
if (s.global && !jQuery.active++) {
// Watch for a new set of requests
jQuery.event.trigger("ajaxStart");
}
var requestDone = false;
// Create the request object
var xml = {};
if (s.global) {
jQuery.event.trigger("ajaxSend", [xml, s]);
}
var uploadCallback = function (isTimeout) {
// Wait for a response to come back
var io = document.getElementById(frameId);
try {
if (io.contentWindow) {
xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;
} else if (io.contentDocument) {
xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;
}
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
if (xml || isTimeout == "timeout") {
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if (status != "error") {
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData(xml, s.dataType);
if (s.success) {
// ifa local callback was specified, fire it and pass it the data
s.success(data, status);
};
if (s.global) {
// Fire the global callback
jQuery.event.trigger("ajaxSuccess", [xml, s]);
};
} else {
jQuery.handleError(s, xml, status);
}
} catch (e) {
status = "error";
jQuery.handleError(s, xml, status, e);
};
if (s.global) {
// The request was completed
jQuery.event.trigger("ajaxComplete", [xml, s]);
};
// Handle the global AJAX counter
if (s.global && ! --jQuery.active) {
jQuery.event.trigger("ajaxStop");
};
if (s.complete) {
s.complete(xml, status);
};
jQuery(io).unbind();
setTimeout(function () {
try {
jQuery(io).remove();
jQuery(form).remove();
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
}, 100);
xml = null;
};
}
// Timeout checker
if (s.timeout > 0) {
setTimeout(function () {
if (!requestDone) {
// Check to see ifthe request is still happening
uploadCallback("timeout");
}
}, s.timeout);
}
try {
var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
if (form.encoding) {
form.encoding = 'multipart/form-data';
}
else {
form.enctype = 'multipart/form-data';
}
jQuery(form).submit();
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
if (window.attachEvent) {
document.getElementById(frameId).attachEvent('onload', uploadCallback);
}
else {
document.getElementById(frameId).addEventListener('load', uploadCallback, false);
}
return { abort: function () { } };
},
/*
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">{"Result":true}</string>
*/
uploadHttpData: function (r, type) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// ifthe type is "script", eval it in global context
if (type == "script") {
jQuery.globalEval(data);
}
// Get the JavaScript object, ifJSON is used.
if (type == "json") {
////////////以下为新增代码///////////////
try{
data = r.responseXML.documentElement.childNodes[0].nodeValue;
} catch (e) {
data = "{}";
}
///////////以上为新增代码///////////////
return JSON.parse(data);
}
// evaluate scripts within html
if (type == "html") {
jQuery("<div>").html(data).evalScripts();
}
if (type == "text")
data = r.responseText;
return data;
},
handleError:function(s, xhr, status, e )
{
// If a local callback was specified, fire it
if ( s.error ) {
s.error.call( s.context || s, xhr, status, e );
}
// Fire the global callback
if ( s.global ) {
(s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
}
}
});

View File

@ -0,0 +1,55 @@
using System.IO;
using System.Web;
using Bootstrap.DataAccess;
using System.Web.Script.Serialization;
using System.Web.Http;
using System;
using System.Drawing;
using System.Drawing.Imaging;
namespace Bootstrap.Admin.Controllers
{
public class InfosController : ApiController
{
[HttpPost]
public string Post()
{
bool ret = false;
var msg = new { Result = ret, img_str = "" };
var files = HttpContext.Current.Request.Files;
if (files.Count > 0)
{
string userName = HttpContext.Current.User.Identity.Name;
if (userName.ToLower() != "argo" && userName.ToLower() != "test")
{
string iconUrl = HttpContext.Current.Server.MapPath("~/Content/images/uploader/");
using (Stream inputStream = files[0].InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
Bitmap bmp = new Bitmap(memoryStream);
if (!Directory.Exists(iconUrl))
Directory.CreateDirectory(iconUrl);
string fileName = DateTime.Now.ToShortDateString().Replace("/", "") + DateTime.Now.Hour.ToString()
+ DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString()
+ DateTime.Now.Millisecond.ToString() + userName + ".jpg"; //图片名称
bmp.Save(iconUrl + fileName, ImageFormat.Jpeg); //保存图片
string headImg = DictHelper.RetrieveUrl() + fileName;
ret = UserHelper.SaveUserHeadImgByName(headImg, userName);
msg = new { Result = ret, img_str = headImg };
}
}
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(msg);
}
}
}

View File

@ -13,6 +13,7 @@ namespace Bootstrap.Admin.Models
public HeaderBarModel()
{
var user = UserHelper.RetrieveUsersByName(HttpContext.Current.User.Identity.Name);
HeadImg = user.HeadImg;
DisplayName = user.DisplayName;
UserName = user.UserName;
UserID = user.ID;
@ -68,6 +69,10 @@ namespace Bootstrap.Admin.Models
/// 获得/设置 消息列表
/// </summary>
public IEnumerable<Message> MessageList { get; set; }
/// <summary>
///
/// </summary>
public string HeadImg { get; set; }
}
}

View File

@ -0,0 +1,46 @@
$(function () {
bindImageSelectListener();
$('#btn_img').click(function () {
$.ajaxFileUpload({
url: '../api/Infos/',
secureuri: false,
fileElementId: 'uploadImg', //上传文件的Name属性
dataType: 'json',
type: 'POST',
success: function (data, status) {
if (data.Result === true) {
swal("成功", "修改头像", "success");
//刷新头像
changeHeaderIcon(data.img_str);
} else if (data.Result === false) {
swal("失败", "网站管理员不允许修改头像", "error");
}
bindImageSelectListener();
},
error: function (data, status, e) {
swal("失败", "修改头像", "error");
bindImageSelectListener();
}
});
return false;
})
})
function changeHeaderIcon(img_str) {
$("#header_img").attr("src", img_str);
}
function bindImageSelectListener() {
$('#uploadImg').on("change", function () {
var file = this.files[0];
if (this.files && file) {
var reader = new FileReader();
reader.onload = function (e) {
$('#headImg').attr("src", e.target.result);
}
reader.readAsDataURL(file);
}
})
}

View File

@ -3,7 +3,13 @@
ViewBag.Title = "个人中心";
Layout = "~/Views/Shared/_Admin.cshtml";
}
@section Javascript {
<script src="~/Content/js/ajaxfileupload.js"></script>
<script src="~/content/js/sweetalert.js"></script>
<script src="~/scripts/Infos.js"></script>
}
@section css {
<link href="~/Content/css/sweetalert.css" rel="stylesheet" />
<link href="~/Content/css/tasks.css" rel="stylesheet" />
}
@section header {
@ -18,24 +24,12 @@
<form class="form-inline" id="infoDataForm" name="infoDataForm" role="form">
<div class="row">
<div class="form-group col-xs-12 col-sm-6">
<label class="control-label" for="realName">真实姓名</label>
<input type="text" class="form-control" id="realName" name="realName" maxlength="50" />
<label class="control-label" for="userName">登陆名称</label>
<input type="text" class="form-control" id="userName" name="userName" placeholder="不可为空" maxlength="50" />
</div>
<div class="form-group col-xs-12 col-sm-6">
<label class="control-label" for="email">邮箱</label>
<input type="text" class="form-control" id="email" name="email" maxlength="50" />
</div>
<div class="form-group col-xs-12 col-sm-6">
<label class="control-label" for="phoneNumber">手机号码</label>
<input type="text" class="form-control" id="phoneNumber" name="phoneNumber" />
</div>
<div class="form-group col-xs-12 col-sm-6">
<label class="control-label" for="birthday">出生年月</label>
<input type="text" class="form-control" id="birthday" name="birthday" />
</div>
<div class="form-group col-xs-12">
<label class="control-label" for="profiles">个人简介</label>
<textarea class="form-control" cols="50" rows="3" id="profiles" name="profiles"></textarea>
<label class="control-label" for="DisplayName">显示名称</label>
<input type="text" class="form-control" id="DisplayName" name="DisplayName" placeholder="不可为空" maxlength="50" />
</div>
</div>
</form>
@ -71,18 +65,18 @@
<div class="panel panel-default">
<div class="panel-heading">修改头像</div>
<div class="panel-body">
<form class="form-inline" id="imgDataForm" name="imgDataForm" role="form">
<form class="form-inline" id="imgDataForm" name="imgDataForm" role="form" >
<div class="row">
<div class="form-group col-xs-12">
<label class="control-label" for="uploadImg">上传头像: </label>
<img class="form-control" src="" id="headImg" width="100" height="100" />
<img class="form-control" src="" id="headImg" width="200" height="200" />
<input class="form-control btn btn-default" type="file" name="uploadImg" id="uploadImg"
accept="image/png,image/gif,image/jpeg,image/tiff,image/vnd.dwg,image/vnd.dxf,image/vnd.svf" />
</div>
</div>
</form>
<div class="modal-footer">
<button class="btn btn-default" type="button">保存</button>
<button class="btn btn-default" type="button" id="btn_img">保存</button>
</div>
</div>
</div>

View File

@ -190,7 +190,14 @@
<!-- user login dropdown start-->
<li class="dropdown">
<a data-toggle="dropdown" class="dropdown-toggle" href="#">
<img alt="" src="~/content/images/logo6.jpg">
@if (Model.HeadImg == null)
{
<img id="header_img" alt="" src="~/content/images/logo6.jpg">
}
else
{
<img id="header_img" alt="" src="@Model.HeadImg">
}
<span class="username">@Model.DisplayName</span>
<b class="caret"></b>
<input id="userId" type="text" class="hide" value="@Model.UserID" />

View File

@ -185,5 +185,15 @@ namespace Bootstrap.DataAccess
}
return ret;
}
/// <summary>
/// 获取头像路径
/// </summary>
/// <returns></returns>
public static string RetrieveUrl()
{
var urls = DictHelper.RetrieveDicts(16);
var url = urls.FirstOrDefault(d => d.Name == "头像路径");
return url.Code;
}
}
}

View File

@ -59,5 +59,9 @@ namespace Bootstrap.DataAccess
/// 获得/设置 拒绝时刻
/// </summary>
public string RejectedTime { get; set; }
/// <summary>
/// 获取/设置 用户头像
/// </summary>
public string HeadImg { get; set; }
}
}

View File

@ -70,7 +70,7 @@ namespace Bootstrap.DataAccess
return CacheManager.GetOrAdd(key, CacheSection.RetrieveIntervalByKey(RetrieveUsersByNameDataKey), k =>
{
User user = null;
string sql = "select ID, UserName, [Password], PassSalt, DisplayName, RegisterTime, ApprovedTime from Users where ApprovedTime is not null and UserName = @UserName";
string sql = "select ID, UserName, [Password], PassSalt, DisplayName, RegisterTime, ApprovedTime, HeadImg from Users where ApprovedTime is not null and UserName = @UserName";
DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql);
try
{
@ -87,7 +87,8 @@ namespace Bootstrap.DataAccess
PassSalt = (string)reader[3],
DisplayName = (string)reader[4],
RegisterTime = (DateTime)reader[5],
ApprovedTime = (DateTime)reader[6]
ApprovedTime = (DateTime)reader[6],
HeadImg = (string)reader[7]
};
}
}
@ -361,5 +362,31 @@ namespace Bootstrap.DataAccess
}
return ret;
}
/// <summary>
/// 根据用户名修改用户头像
/// </summary>
/// <param name="headImg"></param>
/// <param name="userName"></param>
/// <returns></returns>
public static bool SaveUserHeadImgByName(string headImg, string userName)
{
bool ret = false;
try
{
string sql = "Update Users set HeadImg=@HeadImg where UserName=@UserName";
using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql))
{
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@HeadImg", headImg, ParameterDirection.Input));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@UserName", userName, ParameterDirection.Input));
DBAccessManager.SqlDBAccess.ExecuteNonQuery(cmd);
ret = true;
}
}
catch (Exception ex)
{
ExceptionManager.Publish(ex);
}
return ret;
}
}
}

View File

@ -3,7 +3,7 @@ GO
DELETE From Users where ID = 1
SET IDENTITY_INSERT [dbo].[Users] ON
insert into Users (ID, UserName, Password, PassSalt, DisplayName, RegisterTime, ApprovedTime,ApprovedBy, [Description]) values (1, 'Admin', 'Es7WVgNsJuELwWK8daCqufUBknCsSC0IYDphQZAiGOo=', 'W5vpBEOYRGHkQXatN0t+ECM/U8cHDuEgrq56+zZBk4J481xH', 'Administrator', GetDate(), GetDate(), 'system', N'系统默认创建')
insert into Users (ID, UserName, Password, PassSalt, DisplayName, RegisterTime, ApprovedTime,ApprovedBy, [Description],HeadImg) values (1, 'Admin', 'Es7WVgNsJuELwWK8daCqufUBknCsSC0IYDphQZAiGOo=', 'W5vpBEOYRGHkQXatN0t+ECM/U8cHDuEgrq56+zZBk4J481xH', 'Administrator', GetDate(), GetDate(), 'system', N'系统默认创建','http://118.244.234.207:85/Content/images/logo6.jpg')
SET IDENTITY_INSERT [dbo].[Users] OFF
DELETE From Dicts
@ -23,7 +23,7 @@ INSERT [dbo].[Dicts] ([ID], [Category], [Name], [Code], [Define]) VALUES (12, N'
INSERT [dbo].[Dicts] ([ID], [Category], [Name], [Code], [Define]) VALUES (13, N'消息状态', N'已读', N'1', 0)
INSERT [dbo].[Dicts] ([ID], [Category], [Name], [Code], [Define]) VALUES (14, N'消息标签', N'一般', N'0', 0)
INSERT [dbo].[Dicts] ([ID], [Category], [Name], [Code], [Define]) VALUES (15, N'消息标签', N'紧要', N'1', 0)
INSERT [dbo].[Dicts] ([ID], [Category], [Name], [Code], [Define]) VALUES (16, N'上传文件地址', N'头像路径', N'http://118.244.234.207:85/Content/images/uploader/', 0)
SET IDENTITY_INSERT [dbo].[Dicts] OFF
DELETE FROM Navigations

View File

@ -28,6 +28,7 @@ CREATE TABLE [dbo].[Users](
[RejectedBy] [varchar](50) NULL,
[RejectedTime] [datetime] NULL,
[RejectedReason] [nvarchar](50) NULL,
[HeadImg] [varchar](500) NULL,
CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED
(
[ID] ASC