个人中心,自定义头像功能重构

This commit is contained in:
Argo-Lenovo 2016-11-16 17:27:03 +08:00
parent a99a300452
commit bd2b1d78e3
25 changed files with 3960 additions and 369 deletions

View File

@ -109,6 +109,8 @@
<Content Include="Content\css\bootstrap-select.css" />
<Content Include="Content\css\bootstrap-select.min.css" />
<Content Include="Content\css\fa.css" />
<Content Include="Content\css\fileinput.css" />
<Content Include="Content\css\fileinput.min.css" />
<Content Include="Content\css\font-awesome.css" />
<Content Include="Content\css\bootstrap-table.css" />
<Content Include="Content\css\bootstrap-table.min.css" />
@ -124,6 +126,8 @@
<Content Include="Content\css\tasks.css" />
<Content Include="Content\html\RegResult.html" />
<Content Include="Content\images\bg.jpg" />
<Content Include="Content\images\loading-sm.gif" />
<Content Include="Content\images\loading.gif" />
<Content Include="Content\images\lock-bg.jpg" />
<Content Include="Content\images\logo.jpg" />
<Content Include="Content\images\logo1.jpg" />
@ -132,12 +136,15 @@
<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\images\uploader\default.jpg" />
<Content Include="Content\images\uploader\readme.txt" />
<Content Include="Content\js\bootstrap-datetimepicker.js" />
<Content Include="Content\js\bootstrap-select.js" />
<Content Include="Content\js\bootstrap-select.min.js" />
<Content Include="Content\js\defaults-zh_CN.js" />
<Content Include="Content\js\defaults-zh_CN.min.js" />
<Content Include="Content\js\fileinput.js" />
<Content Include="Content\js\fileinput.min.js" />
<Content Include="Content\js\jquery.nestable.js" />
<Content Include="Content\css\site-responsive.css" />
<Content Include="Content\fonts\fontawesome-webfont.svg" />
@ -161,6 +168,7 @@
<Content Include="Content\js\log.js" />
<Content Include="Content\js\longbow.dataentity.js" />
<Content Include="Content\js\moment-with-locales.js" />
<Content Include="Content\js\zh.js" />
<Content Include="Global.asax" />
<Content Include="Content\fonts\glyphicons-halflings-regular.woff2" />
<Content Include="Content\fonts\glyphicons-halflings-regular.woff" />

View File

@ -0,0 +1,401 @@
/*!
* bootstrap-fileinput v4.3.6
* http://plugins.krajee.com/file-input
*
* Author: Kartik Visweswaran
* Copyright: 2014 - 2016, Kartik Visweswaran, Krajee.com
*
* Licensed under the BSD 3-Clause
* https://github.com/kartik-v/bootstrap-fileinput/blob/master/LICENSE.md
*/
.file-loading {
top: 0;
right: 0;
width: 25px;
height: 25px;
font-size: 999px;
text-align: right;
color: #fff;
background: transparent url('../images/loading.gif') top left no-repeat;
border: none;
}
.file-object {
margin: 0 0 -5px 0;
padding: 0;
}
.btn-file {
position: relative;
overflow: hidden;
}
.btn-file input[type=file] {
position: absolute;
top: 0;
right: 0;
min-width: 100%;
min-height: 100%;
text-align: right;
opacity: 0;
background: none repeat scroll 0 0 transparent;
cursor: inherit;
display: block;
}
.file-caption-name {
display: inline-block;
overflow: hidden;
height: 20px;
word-break: break-all;
}
.input-group-lg .file-caption-name {
height: 25px;
}
.file-zoom-dialog {
text-align: left;
}
.file-error-message {
color: #a94442;
background-color: #f2dede;
margin: 5px;
border: 1px solid #ebccd1;
border-radius: 4px;
padding: 15px;
}
.file-error-message pre, .file-error-message ul {
margin: 0;
text-align: left;
}
.file-error-message pre {
margin: 5px 0;
}
.file-caption-disabled {
background-color: #EEEEEE;
cursor: not-allowed;
opacity: 1;
}
.file-preview {
border-radius: 5px;
border: 1px solid #ddd;
padding: 5px;
width: 100%;
margin-bottom: 5px;
}
.file-preview-frame {
position: relative;
display: table;
margin: 8px;
height: 160px;
border: 1px solid #ddd;
box-shadow: 1px 1px 5px 0 #a2958a;
padding: 6px;
float: left;
text-align: center;
vertical-align: middle;
}
.file-preview-frame:not(.file-preview-error):hover {
box-shadow: 3px 3px 5px 0 #333;
}
.file-preview-image {
vertical-align: middle;
image-orientation: from-image;
}
.file-preview-text {
display: block;
color: #428bca;
border: 1px solid #ddd;
font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
outline: none;
padding: 8px;
resize: none;
}
.file-preview-html {
border: 1px solid #ddd;
padding: 8px;
overflow: auto;
}
.file-zoom-dialog .file-preview-text {
font-size: 1.2em;
}
.file-preview-other {
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
text-align: center;
vertical-align: middle;
padding: 10px;
}
.file-preview-other:hover {
opacity: 0.8;
}
.file-actions, .file-other-error {
text-align: left;
}
.file-other-icon {
font-size: 4.8em;
}
/* noinspection CssOverwrittenProperties */
.file-zoom-dialog .file-other-icon {
font-size: 8em;
font-size: 55vmin;
}
.file-input-new .file-preview, .file-input-new .close, .file-input-new .glyphicon-file,
.file-input-new .fileinput-remove-button, .file-input-new .fileinput-upload-button,
.file-input-ajax-new .fileinput-remove-button, .file-input-ajax-new .fileinput-upload-button {
display: none;
}
.file-caption-main {
width: 100%;
}
.file-input-ajax-new .no-browse .input-group-btn,
.file-input-new .no-browse .input-group-btn {
display: none;
}
.file-input-ajax-new .no-browse .form-control,
.file-input-new .no-browse .form-control {
border-top-right-radius: 4px;
border-bottom-right-radius: 4px;
}
.file-thumb-loading {
background: transparent url('../images/loading.gif') no-repeat scroll center center content-box !important;
}
.file-actions {
margin-top: 15px;
}
.file-footer-buttons {
float: right;
}
.file-upload-indicator {
display: inline;
cursor: default;
opacity: 0.8;
width: 60%;
}
.file-upload-indicator:hover {
font-weight: bold;
opacity: 1;
}
.file-footer-caption {
display: block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
width: 160px;
text-align: center;
padding-top: 4px;
font-size: 11px;
color: #777;
margin: 5px auto;
}
.file-preview-error {
opacity: 0.65;
box-shadow: none;
}
.file-preview-frame:not(.file-preview-error) .file-footer-caption:hover {
color: #000;
}
.file-drop-zone {
border: 1px dashed #aaa;
border-radius: 4px;
height: 100%;
text-align: center;
vertical-align: middle;
margin: 12px 15px 12px 12px;
padding: 5px;
}
.file-drop-zone-title {
color: #aaa;
font-size: 1.6em;
padding: 85px 10px;
cursor: default;
}
.file-preview .clickable,
.clickable .file-drop-zone-title {
cursor: pointer;
}
.file-drop-zone.clickable:hover {
border: 2px dashed #999;
}
.file-drop-zone.clickable:focus {
border: 2px solid #5acde2;
}
.file-drop-zone .file-preview-thumbnails {
cursor: default;
}
.file-highlighted {
border: 2px dashed #999 !important;
background-color: #f0f0f0;
}
.file-uploading {
background: url('../images/loading-sm.gif') no-repeat center bottom 10px;
opacity: 0.65;
}
.file-thumb-progress {
height: 10px;
}
.file-thumb-progress .progress, .file-thumb-progress .progress-bar {
height: 10px;
font-size: 9px;
line-height: 10px;
}
.file-thumbnail-footer {
position: relative;
}
.file-thumb-progress {
position: absolute;
top: 35px;
left: 0;
right: 0;
}
.file-zoom-fullscreen.modal {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
.file-zoom-fullscreen .modal-dialog {
position: fixed;
margin: 0;
width: 100%;
height: 100%;
padding: 0;
}
.file-zoom-fullscreen .modal-content {
border-radius: 0;
box-shadow: none;
}
.file-zoom-fullscreen .modal-body {
overflow-y: auto;
}
.file-zoom-dialog .modal-body {
position: relative !important;
}
.file-zoom-dialog .btn-navigate {
position: absolute;
padding: 0;
margin: 0;
background: transparent;
text-decoration: none;
outline: none;
opacity: 0.7;
top: 45%;
font-size: 4em;
color: #1c94c4;
}
.file-zoom-dialog .floating-buttons {
position: absolute;
top: 5px;
right: 10px;
}
.floating-buttons, .floating-buttons .btn {
z-index: 3000;
}
.file-zoom-dialog .kv-zoom-actions .btn,
.floating-buttons .btn {
margin-left: 3px;
}
.file-zoom-dialog .btn-navigate:not([disabled]):hover,
.file-zoom-dialog .btn-navigate:not([disabled]):focus {
outline: none;
box-shadow: none;
opacity: 0.5;
}
.file-zoom-dialog .btn-navigate[disabled] {
opacity: 0.3;
}
.file-zoom-dialog .btn-prev {
left: 1px;
}
.file-zoom-dialog .btn-next {
right: 1px;
}
.file-drag-handle {
display: inline;
margin-right: 2px;
font-size: 16px;
cursor: move;
cursor: -webkit-grabbing;
}
.file-drag-handle:hover {
opacity: 0.7;
}
.file-zoom-content {
height: 480px;
text-align: center;
}
.file-preview-initial.sortable-chosen {
background-color: #d9edf7;
}
.file-preview-frame.sortable-ghost {
background-color: #eee;
}
/* IE 10 fix */
.btn-file ::-ms-browse {
width: 100%;
height: 100%;
}

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 847 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.0 KiB

View File

@ -0,0 +1 @@
请不要删除此目录

View File

@ -1,224 +0,0 @@
// 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] );
}
}
});

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,75 @@
/*!
* FileInput Chinese Translations
*
* This file must be loaded after 'fileinput.js'. Patterns in braces '{}', or
* any HTML markup tags in the messages must not be converted or translated.
*
* @see http://github.com/kartik-v/bootstrap-fileinput
* @author kangqf <kangqingfei@gmail.com>
*
* NOTE: this file must be saved in UTF-8 encoding.
*/
(function ($) {
"use strict";
$.fn.fileinputLocales['zh'] = {
fileSingle: '文件',
filePlural: '个文件',
browseLabel: '选择 &hellip;',
removeLabel: '移除',
removeTitle: '清除选中文件',
cancelLabel: '取消',
cancelTitle: '取消进行中的上传',
uploadLabel: '上传',
uploadTitle: '上传选中文件',
msgNo: '没有',
msgNoFilesSelected: '',
msgCancelled: '取消',
msgZoomModalHeading: '详细预览',
msgSizeTooSmall: 'File "{name}" (<b>{size} KB</b>) is too small and must be larger than <b>{minSize} KB</b>.',
msgSizeTooLarge: '文件 "{name}" (<b>{size} KB</b>) 超过了允许大小 <b>{maxSize} KB</b>.',
msgFilesTooLess: '你必须选择最少 <b>{n}</b> {files} 来上传. ',
msgFilesTooMany: '选择的上传文件个数 <b>({n})</b> 超出最大文件的限制个数 <b>{m}</b>.',
msgFileNotFound: '文件 "{name}" 未找到!',
msgFileSecured: '安全限制,为了防止读取文件 "{name}".',
msgFileNotReadable: '文件 "{name}" 不可读.',
msgFilePreviewAborted: '取消 "{name}" 的预览.',
msgFilePreviewError: '读取 "{name}" 时出现了一个错误.',
msgInvalidFileName: 'Invalid or unsupported characters in file name "{name}".',
msgInvalidFileType: '不正确的类型 "{name}". 只支持 "{types}" 类型的文件.',
msgInvalidFileExtension: '不正确的文件扩展名 "{name}". 只支持 "{extensions}" 的文件扩展名.',
msgUploadAborted: '该文件上传被中止',
msgUploadThreshold: 'Processing...',
msgValidationError: '验证错误',
msgLoading: '加载第 {index} 文件 共 {files} &hellip;',
msgProgress: '加载第 {index} 文件 共 {files} - {name} - {percent}% 完成.',
msgSelected: '{n} {files} 选中',
msgFoldersNotAllowed: '只支持拖拽文件! 跳过 {n} 拖拽的文件夹.',
msgImageWidthSmall: '宽度的图像文件的"{name}"的必须是至少{size}像素.',
msgImageHeightSmall: '图像文件的"{name}"的高度必须至少为{size}像素.',
msgImageWidthLarge: '宽度的图像文件"{name}"不能超过{size}像素.',
msgImageHeightLarge: '图像文件"{name}"的高度不能超过{size}像素.',
msgImageResizeError: '无法获取的图像尺寸调整。',
msgImageResizeException: '错误而调整图像大小。<pre>{errors}</pre>',
dropZoneTitle: '拖拽文件到这里 &hellip;<br>支持多文件同时上传',
dropZoneClickTitle: '<br>(或点击{files}按钮选择文件)',
fileActionSettings: {
removeTitle: '删除文件',
uploadTitle: '上传文件',
zoomTitle: '查看详情',
dragTitle: '移动 / 重置',
indicatorNewTitle: '没有上传',
indicatorSuccessTitle: '上传',
indicatorErrorTitle: '上传错误',
indicatorLoadingTitle: '上传 ...'
},
previewZoomButtonTitles: {
prev: '预览上一个文件',
next: '预览下一个文件',
toggleheader: '缩放',
fullscreen: '全屏',
borderless: '无边界模式',
close: '关闭当前预览'
}
};
})(window.jQuery);

View File

@ -1,55 +1,45 @@
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);
}
}
using Bootstrap.DataAccess;
using Longbow.ExceptionManagement;
using Longbow.Security.Principal;
using System;
using System.Collections.Specialized;
using System.IO;
using System.Web;
using System.Web.Http;
namespace Bootstrap.Admin.Controllers
{
public class InfosController : ApiController
{
[HttpPost]
public string Post()
{
var ret = string.Empty;
var userName = User.Identity.Name;
if (LgbPrincipal.IsAdmin(userName)) userName = "default";
var files = HttpContext.Current.Request.Files;
if (files.Count > 0 && !LgbPrincipal.IsAdmin(userName))
{
var webSiteUrl = DictHelper.RetrieveIconFolderPath().Code;
var fileName = string.Format("{0}.jpg", userName);
var fileUrl = string.Format("{0}{1}", webSiteUrl, fileName);
var filePath = HttpContext.Current.Server.MapPath(fileUrl);
var fileFolder = Path.GetDirectoryName(filePath);
try
{
if (!Directory.Exists(fileFolder)) Directory.CreateDirectory(fileFolder);
files[0].SaveAs(filePath);
ret = string.Format("{0}?q={1}", Url.Content(fileUrl), DateTime.Now.Ticks);
UserHelper.SaveUserIconByName(userName, fileName);
}
catch (Exception ex)
{
var nv = new NameValueCollection();
nv.Add("UpLoadFileName", filePath);
ExceptionManager.Publish(ex, nv);
}
}
return ret;
}
}
}

View File

@ -13,7 +13,7 @@ namespace Bootstrap.Admin.Models
public HeaderBarModel()
{
var user = UserHelper.RetrieveUsersByName(HttpContext.Current.User.Identity.Name);
HeadImg = user.HeadImg;
Icon = user.Icon;
DisplayName = user.DisplayName;
UserName = user.UserName;
UserID = user.ID;
@ -72,7 +72,7 @@ namespace Bootstrap.Admin.Models
/// <summary>
///
/// </summary>
public string HeadImg { get; set; }
public string Icon { get; set; }
}
}

View File

@ -1,46 +1,20 @@
$(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);
}
})
}
$(function () {
var $headerIcon = $('#headerIcon');
var preIcon = $headerIcon.attr('src');
$('#fileIcon').fileinput({
uploadUrl: '../api/Infos',
language: 'zh',
allowedFileExtensions: ['jpg'],
initialPreview: [
preIcon
],
initialPreviewConfig: [
{ caption: "现在头像", size: 730, showZoom: false },
],
initialPreviewAsData: true,
overwriteInitial: true,
}).on('fileuploaded', function (event, data, previewId, index) {
var url = data.response;
if (!!url) $headerIcon.attr('src', url);
});
});

View File

@ -4,13 +4,15 @@
Layout = "~/Views/Shared/_Admin.cshtml";
}
@section Javascript {
<script src="~/Content/js/ajaxfileupload.js"></script>
<script src="~/content/js/sweetalert.js"></script>
<script src="~/content/js/sweetalert.js"></script>
<script src="~/Content/js/fileinput.js"></script>
<script src="~/Content/js/zh.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" />
<link href="~/Content/css/fileinput.css" rel="stylesheet" />
}
@section header {
@Html.Partial("Header", Model)
@ -65,18 +67,10 @@
<div class="panel panel-default">
<div class="panel-heading">修改头像</div>
<div class="panel-body">
<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="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>
<form enctype="multipart/form-data">
<div class="form-group">
<input id="fileIcon" class="file" type="file">
</div>
</form>
<div class="modal-footer">
<button class="btn btn-default" type="button" id="btn_img">保存</button>
</div>
</div>
</div>

View File

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

View File

@ -42,6 +42,7 @@
<add key="LogHelper-RetrieveLogs" interval="600" desc="所有日志数据缓存"/>
<add key="DictHelper-RetrieveDicts" interval="600" desc="所有字典数据缓存"/>
<add key="DictHelper-RetrieveDictsWebSettings" interval="600" desc="网站配置数据缓存"/>
<add key="DictHelper-RetrieveDictsIconPathSettings" interval="600" desc="网站头像目录缓存"/>
<add key="NotificationHelper-RetrieveNotifications" interval="600" desc="通知管理数据缓存"/>
<add key="UserHelper-RetrieveNewUsers" interval="300" desc="新用户数据缓存" />
<add key="ExceptionHelper-RetrieveExceptions" interval="600" desc="程序异常数据缓存"/>

View File

@ -14,14 +14,15 @@ namespace Bootstrap.DataAccess
{
internal const string RetrieveDictsDataKey = "DictHelper-RetrieveDicts";
internal const string RetrieveWebSettingsDataKey = "DictHelper-RetrieveDictsWebSettings";
internal const string RetrieveIconPathSettingsDataKey = "DictHelper-RetrieveDictsIconPathSettings";
/// <summary>
/// 查询所有字典信息
/// </summary>
/// <param name="tId"></param>
/// <returns></returns>
public static IEnumerable<Dict> RetrieveDicts(int id = 0)
public static IEnumerable<Dict> RetrieveDicts()
{
var ret = CacheManager.GetOrAdd(RetrieveDictsDataKey, CacheSection.RetrieveIntervalByKey(RetrieveDictsDataKey), key =>
return CacheManager.GetOrAdd(RetrieveDictsDataKey, CacheSection.RetrieveIntervalByKey(RetrieveDictsDataKey), key =>
{
string sql = "select ID, Category, Name, Code, Define, case Define when 0 then '系统使用' else '自定义' end DefineName from Dicts";
List<Dict> Dicts = new List<Dict>();
@ -47,7 +48,6 @@ namespace Bootstrap.DataAccess
catch (Exception ex) { ExceptionManager.Publish(ex); }
return Dicts;
}, CacheSection.RetrieveDescByKey(RetrieveDictsDataKey));
return id == 0 ? ret : ret.Where(t => id == t.ID);
}
/// <summary>
/// 删除字典中的数据
@ -189,11 +189,34 @@ namespace Bootstrap.DataAccess
/// 获取头像路径
/// </summary>
/// <returns></returns>
public static string RetrieveUrl()
public static Dict RetrieveIconFolderPath()
{
var urls = DictHelper.RetrieveDicts(16);
var url = urls.FirstOrDefault(d => d.Name == "头像路径");
return url.Code;
return CacheManager.GetOrAdd(RetrieveIconPathSettingsDataKey, CacheSection.RetrieveIntervalByKey(RetrieveIconPathSettingsDataKey), key =>
{
string sql = "select ID, Category, Name, Code, Define, case Define when 0 then '系统使用' else '用户自定义' end DefineName from Dicts where Category = N'头像地址' and Name = N'头像路径' and Define = 0";
var dict = new Dict() { Code = "~/Content/images/uploader/" };
DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql);
try
{
using (DbDataReader reader = DBAccessManager.SqlDBAccess.ExecuteReader(cmd))
{
if (reader.Read())
{
dict = new Dict()
{
ID = (int)reader[0],
Category = (string)reader[1],
Name = (string)reader[2],
Code = (string)reader[3],
Define = (int)reader[4],
DefineName = (string)reader[5]
};
}
}
}
catch (Exception ex) { ExceptionManager.Publish(ex); }
return dict;
}, CacheSection.RetrieveDescByKey(RetrieveIconPathSettingsDataKey));
}
}
}

View File

@ -62,6 +62,6 @@ namespace Bootstrap.DataAccess
/// <summary>
/// 获取/设置 用户头像
/// </summary>
public string HeadImg { get; set; }
public string Icon { get; set; }
}
}

View File

@ -65,12 +65,12 @@ namespace Bootstrap.DataAccess
/// <returns></returns>
public static User RetrieveUsersByName(string userName)
{
if (LgbPrincipal.IsAdmin(userName)) return new User() { DisplayName = "网站管理员", UserName = userName };
if (LgbPrincipal.IsAdmin(userName)) return new User() { DisplayName = "网站管理员", UserName = userName, Icon = "~/Content/images/uploader/default.jpg" };
string key = string.Format("{0}-{1}", RetrieveUsersByNameDataKey, userName);
return CacheManager.GetOrAdd(key, CacheSection.RetrieveIntervalByKey(RetrieveUsersByNameDataKey), k =>
{
User user = null;
string sql = "select ID, UserName, [Password], PassSalt, DisplayName, RegisterTime, ApprovedTime, HeadImg from Users where ApprovedTime is not null and UserName = @UserName";
string sql = "select u.ID, UserName, [Password], PassSalt, DisplayName, RegisterTime, ApprovedTime, case isnull(d.Code, '') when '' then '~/Content/images/uploader/' else d.Code end + Icon from Users u left join Dicts d on d.Define = '0' and d.Category = N'头像地址' and Name = N'头像路径' where ApprovedTime is not null and UserName = @UserName";
DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql);
try
{
@ -88,7 +88,7 @@ namespace Bootstrap.DataAccess
DisplayName = (string)reader[4],
RegisterTime = (DateTime)reader[5],
ApprovedTime = (DateTime)reader[6],
HeadImg = (string)reader[7]
Icon = (string)reader[7]
};
}
}
@ -365,22 +365,23 @@ namespace Bootstrap.DataAccess
/// <summary>
/// 根据用户名修改用户头像
/// </summary>
/// <param name="headImg"></param>
/// <param name="userName"></param>
/// <param name="iconName"></param>
/// <returns></returns>
public static bool SaveUserHeadImgByName(string headImg, string userName)
public static bool SaveUserIconByName(string userName, string iconName)
{
bool ret = false;
try
{
string sql = "Update Users set HeadImg=@HeadImg where UserName=@UserName";
string sql = "Update Users set Icon = @iconName 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));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@iconName", iconName, ParameterDirection.Input));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@userName", userName, ParameterDirection.Input));
DBAccessManager.SqlDBAccess.ExecuteNonQuery(cmd);
ret = true;
}
CacheManager.Clear(key => key == RetrieveUsersByNameDataKey);
}
catch (Exception ex)
{

View File

@ -14,7 +14,7 @@ namespace Bootstrap.DataAccess.Tests
[TestInitialize]
public void Initialized()
{
Dict = new Dict() { Category = "__测试字典__", Name = "__测试子字典1__", Code = "2",Define = 0 };
Dict = new Dict() { Category = "__测试字典__", Name = "__测试子字典1__", Code = "2", Define = 0 };
}
[TestCleanup]
@ -44,7 +44,7 @@ namespace Bootstrap.DataAccess.Tests
var dict = dicts.FirstOrDefault(d => d.Category == Dict.Category);
dict.Name = "__测试子字典2__";
Assert.IsTrue(DictHelper.SaveDict(dict), string.Format("更新字典记录ID = {0} 操作失败,请检查 DictHelper.SaveDict 方法", dict.ID));
var dest = DictHelper.RetrieveDicts(dict.ID);
var dest = DictHelper.RetrieveDicts().Where(d => d.ID == dict.ID);
Assert.IsTrue(dest.Count() == 1, "带参数的DictHelper.RetrieveDicts方法调用失败");
Assert.AreEqual(dict.Name, dest.First().Name, string.Format("更新字典记录ID = {0} 操作失败,请检查 DictHelper.SaveDict 方法", dict.ID));
}

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],HeadImg) values (1, 'Admin', 'Es7WVgNsJuELwWK8daCqufUBknCsSC0IYDphQZAiGOo=', 'W5vpBEOYRGHkQXatN0t+ECM/U8cHDuEgrq56+zZBk4J481xH', 'Administrator', GetDate(), GetDate(), 'system', N'系统默认创建','http://118.244.234.207:85/Content/images/logo6.jpg')
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'系统默认创建')
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)
INSERT [dbo].[Dicts] ([ID], [Category], [Name], [Code], [Define]) VALUES (16, N'头像地址', N'头像路径', N'~/Content/images/uploader/', 0)
SET IDENTITY_INSERT [dbo].[Dicts] OFF
DELETE FROM Navigations

View File

@ -28,7 +28,7 @@ CREATE TABLE [dbo].[Users](
[RejectedBy] [varchar](50) NULL,
[RejectedTime] [datetime] NULL,
[RejectedReason] [nvarchar](50) NULL,
[HeadImg] [varchar](500) NULL,
[Icon] [varchar](50) NOT NULL,
CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED
(
[ID] ASC
@ -354,3 +354,6 @@ GO
ALTER TABLE [dbo].[Messages] ADD CONSTRAINT [DF_Messages_Label] DEFAULT ((0)) FOR [Label]
GO
ALTER TABLE [dbo].[Users] ADD CONSTRAINT [DF_Users_Icon] DEFAULT ('default.jpg') FOR [Icon]
GO