文件上传几乎是每个项目所必须的,这里介绍Asp.net MVC结合Jquery ajaxfileupload实现文件上传,兼容主流浏览器
下载ajaxfileupload: ajaxfileupload.js
前端html
图片: | 上传 accept="image/jpg,image/jpeg,image/bmp,image/png" /> .jpg .jpeg .bmp .png 扩展名 |
前端Css
.fileinput-button {
position: relative;
overflow: hidden;
float: left;
margin-right: 4px;
color: #fff;
}
.btn_color_2 {
border: 1px solid transparent;
background-color: #428bca;
}
.btn_upload {
display: inline-block;
margin-bottom: 0;
font-size: 12px;
line-height: 25px;
text-align: center;
white-space: nowrap;
vertical-align: middle;
cursor: pointer;
background-image: none;
border-radius: 4px;
width: 60px;
height: 25px;
color: #fff;
border-color: #357ebd;
}
.fileinput-button input {
position: absolute;
top: 0;
right: 0;
margin: 0;
border: solid transparent;
border-width: 0 0 100px 200px;
opacity: 0;
filter: alpha(opacity=0);
cursor: pointer;
display: block;
align-items: baseline;
color: inherit;
text-align: start;
color: #fff;
}
前端Js$(function () {
$(document).on("change", '#fileUploadHead', function () {
UploadFile("", "fileUploadHead", "/home/UploadFile"
, "Person", function (json, status) {
//alert(JSON.stringify(json));
if (json && json.Success) {
console.log(json);
$("#HeadImg").empty();
var imgElement = ""
+ " "
+ "";
//显示图片
$("#HeadImg").append(imgElement);
} else {
util.MsgBox.info(json.Msg);
}
});
});
});
//关闭页面的时候记得解除绑定,否则会出现触发多次的情况(写在关闭页面方法内)
$(document).off("change", "#fileUploadHead");
$("#fileUploadHead").unbind("click");
// panel: 当前面板id或对话框id , 不带 # 符号;
// fileId: type=file html元素的id, 不带 # 符号;
// 上传文件的 url
// 附属 属性数据(或 防跨域攻击标签)
// callback :回调函数,即上传文件后的接收 返回数据 函数
function UploadFile(panelId, fileId, url, ant, callback) {
//$("#" + fileId).ajaxStart(function () {
var maskId = (panelId == null || panelId == "") ? ("body") : ("#" + panelId);
showLoading(maskId, '正在上传,请稍候...');
//});
$.ajaxFileUpload
(
'',
{
url: url,
secureuri: false,
fileElementId: fileId,
dataType: 'text',
success: function (json, status) {
json = JSON.parse(json);
closeLoading();
if (callback != null)
callback(json, status);
},
error: function (json, status, e) {
closeLoading();
switch (XMLHttpRequest.status) {
case 500:
alert('服务器非常忙碌,请稍候再试...');
break;
case 401:
alert('您没有访问权限,请重新登录!');
break;
case 405:
alert('登录超时,请重新登录!');
break;
case 200:
break;
default:
alert('请检查网络是否正常,请稍候再试...');
break;
}
},
complete: function () {
$("#" + fileId).val("");
}
}
)
};
后端保存文件代码///
/// 上传文件处理(公共)
///
///
///
[HttpPost]
public ContentResult UploadFile(HttpPostedFileBase uploadFileData)
{
ResMsgModel model = new ResMsgModel();
model.Success = false;
if (Request.Form["uploadfile_ant"] == null)
{
model.Msg = "请设置参数:ant, 参照web.config中 FileKit->Catalog->Key的值!";
return Content(Newtonsoft.Json.JsonConvert.SerializeObject(model));
}
string key = Request.Form["uploadfile_ant"].ToString();
CatalogElement catalogConfig = FileCatalogHelper.Catalog[key];
string extenName = Path.GetExtension(uploadFileData.FileName);
if (catalogConfig.FileTypeLimit.ToUpper().IndexOf(extenName.ToUpper())
{
model.Msg = string.Format("请上传文件格式:{0} !", catalogConfig.FileTypeLimit);
return Content(Newtonsoft.Json.JsonConvert.SerializeObject(model));
}
int fileSizeMax = int.Parse(catalogConfig.FileSize) * 1024 * 1024;
if (uploadFileData.ContentLength > fileSizeMax)
{
model.Msg = string.Format("上传文件必须小于等于 {0}MB", catalogConfig.FileSize);
return Content(Newtonsoft.Json.JsonConvert.SerializeObject(model));
}
model.Data = new UploadFileModel();
model.Data.Catalog = DateTime.Now.ToString("yyyyMMdd");
string filePath = Path.Combine(catalogConfig.TempFile.AbsolutePath, model.Data.Catalog);
if (!Directory.Exists(filePath))
Directory.CreateDirectory(filePath);
model.Data.FileName = string.Format("{0}{1}", Guid.NewGuid().ToString("N"), extenName);
filePath = Path.Combine(filePath, model.Data.FileName);
uploadFileData.SaveAs(filePath);
model.Data.Url = string.Format("{0}/{1}/{2}", catalogConfig.TempFile.RelativePath
, model.Data.Catalog, model.Data.FileName);
model.Success = true;
model.Msg = "成功!";
return Content(Newtonsoft.Json.JsonConvert.SerializeObject(model));
}public class ResMsgModel
{
public bool Success { set; get; }
public string Msg { set; get; }
}
public class ResMsgModel : ResMsgModel
{
public T Data { set; get; }
}
///
/// 上传文件 返回数据模型
///
public class UploadFileModel
{
///
/// 目录名称
///
public string Catalog { set; get; }
///
/// 文件名称,包括扩展名
///
public string FileName { set; get; }
///
/// 浏览路径
///
public string Url { set; get; }
}
showLoading()、closeLoading() 请参考:Jquery 生成加载中遮罩层
CatalogElement 操作方法请参考:Asp.Net MVC 自定义配置文件节点
效果图