最近在写实验室管理系统中的个人信息模块,上边要求实现更改头像功能。百度了一大堆,无实用的。(要么各种币)
本文介绍的只是实现了简单功能(毕竟现在初学阶段)
需要引用文件,顺序也不能错。
<script src="~/JS/bootstrap/js/jquery.min.js"></script>
<script src="~/JS/bootstrap/js/bootstrap.min.js"></script>
<script src="~/JS/jquery.ui.widget.js"></script>
<script src="~/JS/jquery.iframe-transport.js"></script>
<script src="~/JS/jquery.fileupload.js"></script>
文件链接:http://pan.baidu.com/s/1skH0xnZ
<div class="widget-user-image">
<img class="img-circle" id="appear" src="../../images/user.jpg" alt="User Avatar" >
</div>
<input type="file" id="fileupload" name="files" multiple>
<button class=" btn btn-primary" id="Start">修改头像</button>
jQuery
<script type="text/javascript">
$(‘#fileupload‘).fileupload({
url: "/Info/img",
Type: "POST",
dataType: ‘json‘,
autoUpload: true,
acceptFileTypes: "/(\.|\/)(gif|jpe?g|png|xlsx)$/i",
add: function (e, data) {
$("#Start").click(function () {
data.submit();
})
alert("已选择文件,可以更新头像!");
},
success: function (response, status) {
var obj = JSON.parse(response);
var imgPath = "../.." + obj["filePath"];
//$("#imglist").append(‘<li><img src="‘ + imgPath + ‘" /> </li>‘);
$(‘#appear‘).attr("src",imgPath);
},
done: function (e, data) {
alert("update finish");
},
error: function (error) {
alert("error");
},
});
</script>
C#方法
public JsonResult img(HttpPostedFileBase files) { try { string localPath = "/images"; string path = Server.MapPath("~" + localPath); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } //TimeSpan ts = DateTime.Now - TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); //string fileName = (long)ts.TotalMilliseconds + Path.GetExtension(files.FileName); string fileName = files.FileName; files.SaveAs(path + "/" + fileName); return Json("{\"filePath\":\"" + localPath + "/" + fileName + "\",\"sourePath\":\"" + files.FileName + "\"}"); } catch (Exception ex) { return null; } }
可以实现简单头像更新。至此
原文:http://www.cnblogs.com/Tinamei/p/6725946.html