一个更换用户头像的示例,需要引用Jquery:
前端。使用一个input tyle=file 用于让用户选择上传的文件。并且隐藏这个html控件,通过其他方式唤起。
<%--上传图片改变用户头像--%> <input type="file" id="photoUpload" style="display: none" accept="image/jpeg,image/png,image/gif" title="更换头像" />当用户点击头像框,激活选择文件对话框。激发input的click事件。
$("#u-photo").click(function () {
if (username.length > 0) {
if (confirm("更换头像,确定?")) {
$("#photoUpload").click();
}
}
else {
if (confirm("前往登陆,确定?")) {
window.location.href="<%=ResolveUrl("/account/login.aspx") %>" + "?url=" + window.location.href;
}
}
});
当用户选定文件后,使用ajax上传文件到服务器
$("#photoUpload").change(function myfunction() {
var upfile = $('#photoUpload').prop("files")[0];
//$('#u-photo').attr("src", $('#photoUpload').val());
var reader = new FileReader();
reader.readAsDataURL(upfile);
reader.onloadend = function () {
var img_base = reader.result;//要上传的图片的base64编码
$("#u-photo").attr("src", img_base);//替换显示的图片
if (img_base.length>170000) {
alert('图片过大,应小于100K,请减小图片尺寸,推荐100x100'); return;
}
var img_path = $('#photoUpload').val();//获取上传图片路径,为获取图片类型使用
$.ajax({
url: '<%=ResolveUrl("~/user.asmx/UploadPhoto") %>', //调用WebService的地址和方法名称组合 ---- WsURL/方法名
ContentType: "application/json;charset=utf-8", //WebService 会返回Json类型
dataType: "json",
type: "Post", //访问WebService使用Post方式请求
data:"{filebytes:\""+img_base+"\"}",
beforeSend: function (x) {
x.setRequestHeader("Content-Type", "application/json; charset=utf-8");
},
success: function (result) {//回调函数,result,返回值
r = result.d;
if (r.IsSuccess) {
alert(r.MsgAlert);
} else {
alert(r.MsgAlert);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("没有登陆");
},
async: false,
});
}
});
后台写一个webservice
//上传用户头像发生
[WebMethod(EnableSession = true)]
public ResponseResult UploadPhoto(string filebytes)
{
ResponseResult result = new ResponseResult();
string username = "";
try
{
username = Convert.ToString(HttpContext.Current.Session["username"]);
}
catch (Exception ex)
{
result.IsSuccess = false;
result.MsgAlert = "请登陆后再操作,错误:"+ex.Message;
return result;
}
if (username.Length > 0)
{
if (filebytes.Length> 170000)
{
result.IsSuccess = false;
result.MsgAlert = "图片过大,应小于100K,请减小图片尺寸,推荐100x100";
return result;
}
var arr=filebytes.Split(',');//去掉开头格式声明
byte[] bytes = Convert.FromBase64String(arr[1]);
var strUploadPath = HttpContext.Current.Server.MapPath("") + "/files/UserPhoto";//+ DateTime.Now.ToString("yy-MM") + "\\" + username
if (!Directory.Exists(strUploadPath))
{
Directory.CreateDirectory(strUploadPath);
}
string strImgPath = strUploadPath + "/" + username+".jpeg";
using (FileStream objfilestream = new FileStream(strImgPath, FileMode.Create, FileAccess.ReadWrite))
{
objfilestream.Write(bytes, 0, bytes.Length);
}
ChangeUserPhoto(username, BlogHelpper.MyWebSite+ "files/UserPhoto/" + username + ".jpeg", "saws1w111ooo");
result.IsSuccess = true;
result.MsgAlert = "更换成功,如不显示请尝试刷新浏览器/清除浏览器缓存";
}
else
{
result.IsSuccess = false;
result.MsgAlert = "服务器数据获取失败";
return result;
}
return result;
}
注意事项:
base64开头带文件标识名,用逗号分割的,转换为bytes之前需要去掉。同时为了验证用户,webService需要启用session。