C#结合HTML实现图片上传
效果预览
HTML
<table>
<tr>
<td rowspan="5" style="background:#ffffff">
<div style="height:140px;width:140px;border-radius:50px;text-align:center;margin:0 auto;">
<img id="Image" style="width:140px;height:140px;border-radius:50%;">
@*不让页面显示文件上传按钮,而是通过点击图片进行文件上传*@
<input id="uploadImage" name="file" accept=".png,.jpg,.jpeg" type="file" style="display: none">
<input id="ImageVal" style="display:none" />
</div>
</td>
</tr>
</table>
JS
$(document).ready(function () {
//图片上传控件初始化
uploadImg.initUploadImg();
})
//头像上传相关
var uploadImg = {
initUploadImg: function () {
$("#Image").click(function () {
setTimeout(function () {
$("#uploadImage").click(); //隐藏了input:file样式后,点击头像就可以本地上传
}, 300);//这个地方做了延时点击,也可以去掉,直接 $("#uploadImage").click();
$("#uploadImage").on("change", function () {
var objType = uploadImg.getObjectType(this.files[0]);
if (objType == "jpg" || objType == "png" || objType == "jpeg") {
var objUrl = uploadImg.getObjectURL(this.files[0]); //获取图片的路径,该路径不是图片在本地的路径
if (objUrl) {
$("#Image").attr("src", objUrl); //将图片路径存入src中,显示出图片
uploadImg.upimg();
}
} else {
alert("请上传jpg|png|jpeg类型的图片");
}
});
});
},
upimg:function () {
var Image = $('#uploadImage')[0].files[0];
var file = new FormData();
file.append('file', Image);
$.ajax({
url: "/Resource/upload",
type: "post",
data: file,
cache: false,
contentType: false,
processData: false,
success: function (data) {
if (data) {
if (data.Success) {
$("#Image").attr("src", data.Data);
$("#ImageVal").val(data.Data);
} else {
alert(data.Message);
}
}
}
});
},
getObjectType: function (file) {
var type = "";
if (file != null) {
var typeSplit = file.type.split("/");
if (typeSplit.length == 2) {
type = typeSplit[1].toLowerCase();
}
}
return type;
},
getObjectURL: function (file) {
var url = null;
if (window.createObjectURL != undefined) { // basic
url = window.createObjectURL(file);
} else if (window.URL != undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file);
} else if (window.webkitURL != undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file);
}
return url;
},
}
C#后台
/// <summary>
/// 上传图片
/// </summary>
/// <param name="Path"></param>
/// <returns></returns>
public JsonResult upload()
{
string Path = "\\Upload\\WorkerFiles";//需要保存图片的地址
BaseReturn ret = new BaseReturn();
try
{
HttpPostedFileBase fileData = Request.Files["file"];
if (fileData != null && fileData.ContentLength > 0)
{
string fileSavePath = Server.MapPath("~") + Path;
int size = fileData.ContentLength;
//获取文件的扩展名
string extName = System.IO.Path.GetExtension(fileData.FileName);
//获取配置文件的合法后缀名称
string strLegalExts = ".png,.jpg,.jpeg";
var extList = strLegalExts.Split(',').ToList();
extList.ForEach(i => i.ToLower());
//如果上传的文件后缀是合法的
if (extList.Contains(extName.ToLower()))
{
//得到一个新文件的名称
string newName = Guid.NewGuid().ToString() + extName;
//如果文件目录不存在 创建目录
if (!System.IO.Directory.Exists(fileSavePath))
{
System.IO.Directory.CreateDirectory(fileSavePath);
}
//服务器保存文件
string path = System.IO.Path.Combine(fileSavePath, newName);
fileData.SaveAs(path);
List<string> FilsDicNames = Path.Split('\\').Where(i => !string.IsNullOrEmpty(i)).ToList();
foreach (var item in FilsDicNames)
{
ret.Data = ret.Data + ("/" + item);
}
ret.Data=ret.Data+"/" + newName;//返回图片路径
ret.Success = true;
}
else
{
ret.Success = false;
ret.Message = "上传失败,请上传正确格式的图片";
}
}
}
catch (Exception ex)
{
ret.Success = false;
ret.Message = "图片上传失败!";
LogUtils.Instance.LogWithDir(LogType.错误, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name, System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString());
}
return Json(ret, JsonRequestBehavior.DenyGet);
}