0、效果图
1、引入js、css(建议css放在html头部,js加载在html底部)
2、html
//上传按钮 multiple为可多文件上传
//保存文件路径
3、初始化
$("#uploaddoc").fileinput({
language: 'zh',
uploadUrl: '/Form/upload',//后台上传方法
allowedFileExtensions: ['doc', 'docx'],//上传文件扩展名
shouUpload: false,
showRemove: false,
browseClass: 'btn btn-danger',
maxFileSize: 5000,
maxFileNum: 10,
allowedPreviewTypes: null,
previewFileIconSettings: {
'doc': ''
},
previewFileExtSettings: {
'doc': function (ext) {
return ext.match(/(doc|docx)$/i);
}
}
});
4、回调方法
var List = new Array();//声明保存上传文件路径数组对象
//上传 - 删除
$('#uploaddoc').on('filesuccessremove', function (event, key) {
var abort = true;
if (confirm("确定要删除已上传的文件吗?")) {
abort = false;
}
var index1;
$.each(List, function (index, item) {
if (item.KeyID == key) {//默认fileinput.js的key与KeyID不一致,需要改动源码,详情见下文
index1 = index;
$.post("/Form/uploaddelete", { key: item.KeyID, path: item.path });//删除以上传到本地的文件
}
});
List.splice(index1, 1);
var path = "";
$.each(List, function (index, item) {
path += item.path;
});
$("#Doc").val(path);//修改保存的文件路径
});
//取消上传事件,左上角的取消按钮
$('#uploaddoc').on('filecleared', function (event, files) {
$.each(List, function (index, item) {
$.post("/Form/uploaddelete", { key: "all", path: item.path });
});
List = new Array();//清空保存的文件路径数组对象,这里是赋值给新的空对象,应该可以优化为删除以保存的所有值
$("#Doc").val("");
});
//上传 - 成功
$("#uploaddoc").on("fileuploaded", function (event, data, previewId, index) {
var form = data.form, files = data.files, extra = data.extra,
response = data.response, reader = data.reader;
List.push({ path: response.path, KeyID: previewId })
$("#Doc").val($("#Doc").val() + response.path);
//$("#Doc").val(List);
});
5、后台上传方法
//上传方法
public JsonResult Upload()
{
HttpPostedFileBase file = Request.Files["file"];
if (file == null)
{
return Json(new { error = "上传异常" });
}
var ext = Path.GetExtension(file.FileName);
var filename = Path.GetFileNameWithoutExtension(file.FileName);
var serverfilenname = Guid.NewGuid().ToString("n") + "_" + filename + ext;
try
{
var path = "/File";
var dic = string.Format("{0}/{1}/{2}/{3}", path, DateTime.Today.Year.ToString(), DateTime.Today.Month.ToString(), DateTime.Today.Day.ToString());
if (!Directory.Exists(Server.MapPath(dic)))
{
Directory.CreateDirectory(Server.MapPath(dic));
}
var webpath = string.Format("{0}/{1}", dic, serverfilenname);
var serverpath = Path.Combine(Server.MapPath(dic), serverfilenname);
file.SaveAs(serverpath);
return Json(new {
url = "/Form/uploaddelete",//定义要删除的action,没有用到可删掉
key = serverfilenname,
path = webpath });
}
catch (Exception ex)
{
return Json(new { error = "上传异常" + ex });
}
}
//删除本地文件方法
public JsonResult UpLoadDelete()
{
try
{
var key = Request.Params["key"];
var path = Request.Params["path"];
if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(path))
{
return Json(false, JsonRequestBehavior.DenyGet);
}
path = Server.MapPath(path);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
return Json(true, JsonRequestBehavior.DenyGet);
}
else
{
return Json(false, JsonRequestBehavior.DenyGet);
}
}
catch (Exception)
{
return Json(false, JsonRequestBehavior.DenyGet);
}
}
6、缺点
尚未研究预览功能
尚有优化空间
7、说明
代码粘贴后可直接使用,后台框架为.net mvc5,默认母版页有加载bootstrap样式和js 如无样式请添加对bootstrap的脚本引用
插件api地址:http://plugins.krajee.com/file-input#events
上网查了好多相关资料 都不完整,最后只有这个api可以看了,最后终于找到左上角关闭按钮的回调事件
参考博客地址:
http://blog.csdn.net/xumoqiu/article/details/53081352?locationNum=1&fps=1
https://izk.cloud/463/