文件上传类
FileUpload.htm
- jQuery JavaScript Library v1.11.1
- jQuery EasyUI 1.3.4
- 文件上传参考 https://github.com/funnyque/easyUpload.js
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" type="text/css" href="../../Styles/easy_upload.css"/>
<style type="text/css">
.fu_list {
width: 100%;
background: #ebebeb;
font-size: 12px;
overflow: auto;
}
.fu_list td {
padding: 5px;
line-height: 20px;
background-color: #fff;
}
.fu_list table {
width: 100%;
border: 1px solid #ebebeb;
}
.fu_list thead td {
background-color: #f4f4f4;
}
.fu_list b {
font-size: 14px;
}
#form1 {
overflow: auto;
height: 300px;
}
/*file容器样式*/
a.files {
width: 90px;
height: 30px;
overflow: hidden;
display: block;
border: 1px solid #BEBEBE;
background: url(../images/img/fu_btn.gif) left top no-repeat;
text-decoration: none;
}
a.files:hover {
background-color: #FFFFEE;
background-position: 0 -30px;
}
/*file设为透明,并覆盖整个触发面*/
a.files input {
margin-left: -350px;
font-size: 30px;
cursor: pointer;
filter: alpha(opacity=0);
opacity: 0;
}
/*取消点击时的虚线框*/
a.files,
a.files input {
outline: none;
/*ff*/
hide-focus: expression(this.hideFocus=true);
/*ie*/
}
</style>
<script type="text/javascript" src="../../Scripts/jquery.min.js"></script>
<script type="text/javascript" src="../../Scripts/jquery.easyui.min.js"></script>
<script type="text/javascript" src="../../Scripts/easyUpload.js"></script>
<title>附件上传</title>
</head>
<body>
<div id="form1">
<form id="uploadForm" action="../../ashx/Flow/File.ashx" method="post">
<table border="0" cellspacing="1" class="fu_list">
<thead>
<tr>
<td colspan="2"><b>上传文件</b>
</td>
</tr>
</thead>
<tbody>
<tr>
<td align="right" width="15%" style="line-height:35px;">添加文件:</td>
<td>
<a href="javascript:void(0);" class="files" id="idFile"></a>
<img id="idProcess" style="display:none;" src="../images/img/loading.gif" alt=""/>
<input id="BillCode" name="BillCode" type="hidden"/>
</td>
</tr>
<tr>
<td colspan="2">
<table border="0" cellspacing="0">
<thead>
<tr>
<td>文件路径</td>
<td width="100"></td>
</tr>
</thead>
<tbody id="idFileList">
</tbody>
</table>
</td>
</tr>
<tr>
<td colspan="2" style="color:gray">温馨提示:最多可同时上传 <b id="idLimit"></b> 个文件,只允许上传 <b id="idExt"></b> 文件。
</td>
</tr>
<tr>
<td colspan="2" align="center" id="idMsg">
<input type="button" value="开始上传" id="idBtnupload" disabled="disabled"/>
<input type="button" value="全部取消" id="idBtndel" disabled="disabled"/>
</td>
</tr>
</tbody>
</table>
</form>
<form id="uploadFormNew" action="../../ashx/Flow/File.ashx" method="post">
<table border="0" cellspacing="1" class="fu_list">
<thead>
<tr>
<td colspan="2"><b>上传文件</b>
</td>
</tr>
</thead>
<tbody>
<!-- <input id="BillCode" name="BillCode" type="hidden"/>-->
<div id="easy1" class="easy-upload">
</div>
</tbody>
</table>
</form>
</div>
<script type="text/javascript">
var isIE = !+'\v1' ? true : false;
var $ = function (id) {
return "string" == typeof id ? document.getElementById(id) : id;
};
var Class = {
create: function () {
return function () {
this.initialize.apply(this, arguments);
}
}
}
var Extend = function (destination, source) {
for (var property in source) {
destination[property] = source[property];
}
}
var Bind = function (object, fun) {
return function () {
return fun.apply(object, arguments);
}
}
var Each = function (list, fun) {
for (var i = 0, len = list.length; i < len; i++) {
fun(list[i], i);
}
};
//文件上传类
var FileUpload = Class.create();
FileUpload.prototype = {
//表单对象,文件控件存放空间
initialize: function (form, folder, options) {
this.Form = $(form); //表单
this.Folder = $(folder); //文件控件存放空间
this.Files = []; //文件集合
this.SetOptions(options);
this.FileName = this.options.FileName;
this._FrameName = this.options.FrameName;
this.Limit = this.options.Limit;
this.Distinct = !!this.options.Distinct;
this.ExtIn = this.options.ExtIn;
this.ExtOut = this.options.ExtOut;
this.onIniFile = this.options.onIniFile;
this.onEmpty = this.options.onEmpty;
this.onNotExtIn = this.options.onNotExtIn;
this.onExtOut = this.options.onExtOut;
this.onLimite = this.options.onLimite;
this.onSame = this.options.onSame;
this.onFail = this.options.onFail;
this.onIni = this.options.onIni;
if (!this._FrameName) {
//为每个实例创建不同的iframe
this._FrameName = "uploadFrame_" + Math.floor(Math.random() * 1000);
//ie不能修改iframe的name
var oFrame = isIE ? document.createElement("<iframe name=\"" + this._FrameName + "\">") : document.createElement("iframe");
//为ff设置name
oFrame.name = this._FrameName;
oFrame.style.display = "none";
//在ie文档未加载完用appendChild会报错
document.body.insertBefore(oFrame, document.body.childNodes[0]);
}
//设置form属性,关键是target要指向iframe
this.Form.target = this._FrameName;
this.Form.method = "post";
//注意ie的form没有enctype属性,要用encoding
this.Form.encoding = "multipart/form-data";
//整理一次
this.Ini();
},
//设置默认属性
SetOptions: function (options) {
this.options = { //默认值
FileName: "", //文件上传控件的name,配合后台使用
FrameName: "", //iframe的name,要自定义iframe的话这里设置name
onIniFile: function () {
}, //整理文件时执行(其中参数是file对象)
onEmpty: function () {
}, //文件空值时执行
Limit: 0, //文件数限制,0为不限制
onLimite: function () {
}, //超过文件数限制时执行
Distinct: true, //是否不允许相同文件
onSame: function () {
}, //有相同文件时执行
ExtIn: [], //允许后缀名
onNotExtIn: function () {
}, //不是允许后缀名时执行
ExtOut: [], //禁止后缀名,当设置了ExtIn则ExtOut无效
onExtOut: function () {
}, //是禁止后缀名时执行
onFail: function () {
}, //文件不通过检测时执行(其中参数是file对象)
onIni: function () {
} //重置时执行
};
Extend(this.options, options || {});
},
//整理空间
Ini: function () {
//整理文件集合
this.Files = [];
//整理文件空间,把有值的file放入文件集合
Each(this.Folder.getElementsByTagName("input"), Bind(this, function (o) {
if (o.type == "file") {
o.value && this.Files.push(o);
this.onIniFile(o);
}
}))
//插入一个新的file
var file = document.createElement("input");
file.name = this.FileName;
file.type = "file";
file.onchange = Bind(this, function () {
this.Check(file);
this.Ini();
});
this.Folder.appendChild(file);
//执行附加程序
this.onIni();
},
//检测file对象
Check: function (file) {
//检测变量
var bCheck = true;
//空值、文件数限制、后缀名、相同文件检测
if (!file.value) {
bCheck = false;
this.onEmpty();
} else if (this.Limit && this.Files.length >= this.Limit) {
bCheck = false;
this.onLimite();
} else if (!!this.ExtIn.length && !RegExp("\.(" + this.ExtIn.join("|") + ")$", "i").test(file.value)) {
//检测是否允许后缀名
bCheck = false;
this.onNotExtIn();
} else if (!!this.ExtOut.length && RegExp("\.(" + this.ExtOut.join("|") + ")$", "i").test(file.value)) {
//检测是否禁止后缀名
bCheck = false;
this.onExtOut();
} else if (!!this.Distinct) {
Each(this.Files, function (o) {
if (o.value == file.value) {
bCheck = false;
}
})
if (!bCheck) {
this.onSame();
}
}
//没有通过检测
!bCheck && this.onFail(file);
},
//删除指定file
Delete: function (file) {
//移除指定file
this.Folder.removeChild(file);
this.Ini();
},
//删除全部file
Clear: function () {
//清空文件空间
Each(this.Files, Bind(this, function (o) {
this.Folder.removeChild(o);
}));
this.Ini();
}
}
var fu = new FileUpload("uploadForm", "idFile", {
Limit: 10,
ExtIn: [],
onIniFile: function (file) {
file.value ? file.style.display = "none" : this.Folder.removeChild(file);
},
onEmpty: function () {
alert("请选择一个文件");
},
onLimite: function () {
alert("超过上传限制");
},
onSame: function () {
alert("已经有相同文件");
},
onNotExtIn: function () {
alert("只允许上传" + this.ExtIn.join(",") + "文件");
},
onFail: function (file) {
this.Folder.removeChild(file);
},
onIni: function () {
//显示文件列表
var arrRows = [];
if (this.Files.length) {
var oThis = this;
Each(this.Files, function (o) {
var a = document.createElement("a");
a.innerHTML = "取消";
a.href = "javascript:void(0);";
a.onclick = function () {
oThis.Delete(o);
return false;
};
arrRows.push([o.value, a]);
});
} else {
arrRows.push(["<font color='gray'>没有添加文件</font>", " "]);
}
AddList(arrRows);
//设置按钮
$("idBtnupload").disabled = $("idBtndel").disabled = this.Files.length <= 0;
}
});
$("idBtnupload").onclick = function () {
//显示文件列表
var arrRows = [];
Each(fu.Files, function (o) {
arrRows.push([o.value, " "]);
});
AddList(arrRows);
fu.Folder.style.display = "none";
$("idProcess").style.display = "";
$("idMsg").innerHTML = "正在添加文件到服务器,请稍候……<br />有可能因为网络问题,出现程序长时间无响应,请点击“<a href='?'><font color='red'>取消</font></a>”重新上传文件";
fu.Form.submit();
}
$("idLimit").innerHTML = fu.Limit;
$("idExt").innerHTML = fu.ExtIn.join(",");
$("idBtndel").onclick = function () {
fu.Clear();
}
document.getElementById('BillCode').value = parent.BillCode; // getQueryString("BillCode");
document.getElementById('uploadForm').action = '../../ashx/Flow/File.ashx?BillCode=' + parent.BillCode;
//js判断是否是ie浏览器且给出ie版本
function IEVersion() {
var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器
var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器
var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1; //判断是否IE11浏览器
if (isIE) {
var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
reIE.test(userAgent);
var fIEVersion = parseFloat(RegExp["$1"]);
if (fIEVersion == 7) {
return 7;
} else if (fIEVersion == 8) {
return 8;
} else if (fIEVersion == 9) {
return 9;
} else if (fIEVersion == 10) {
return 10;
} else {
return 6;//IE版本<=7
}
} else if (isEdge) {
// return 'edge';//edge
return -1;//不是ie浏览器
} else if (isIE11) {
return 11; //IE11
} else {
return -1;//不是ie浏览器
}
}
function init() {
var ieV = IEVersion();
// alert(ieV);
//非IE 执行预览
if (-1 === ieV) {
document.getElementById("uploadForm").style.display = "none";
// $("#form1").attr ("style","display:none;");// 隐藏 div
// $("#form1").css ("display","none");// 隐藏 div
// $("#form1").hide();
} else {
document.getElementById("uploadFormNew").style.display = "none";
if (8 === ieV || 7 === ieV) {
$("#uploadFormNew").attr("style", "display:none");
} else if (6 === ieV) {
document.getElementById("uploadFormNew").style.display = "none";
} else {
document.getElementById("uploadFormNew").style.display = "none";
$("#uploadFormNew").hide();
}
}
}
//初始化执行
window.onload = init;//不要括号
//alert(document.getElementById('BillCode').value);
//var isIE = (document.all) ? true : false;
//新文件上传开始 2022-10-8
//创建另个一实例如下
easyUpload({
easyId: 'easy1',
action: '/ashx/Flow/File.ashx?BillCode=' + parent.BillCode,
// action: '/ashx/Flow/File.ashx?method=ajaxFileUpload&BillCode=' + parent.BillCode,
accept: '.tiff,.tif,.jpg,.png,.bmp,.jpeg,.pdf,.doc,.docx,.xls,.xlsx,.ppt',
maxSize: 4,
maxCount: 10, //插件单次添加文件的最大数量,Number类型
showLoading: true,
setRequestHeader: function (xhr) {
xhr.setRequestHeader('enctype', 'multipart/form-data');
},
buildSendData: function (file) {
var formData = new FormData(); // 发送格式为formData时
formData.append('idFile', file.file);
return formData;
// return file.base64; //发送格式为base64时
// return null; //发送空数据,用于测试
},
checkSuccessCode: function (xhr) {
if (/error/.test(xhr.responseText.toLowerCase())) { //这里判断仅仅用于测试,具体看项目
return false;
} else {
console.log(xhr);
return true;
}
}
});
//新文件上传结束
//旧文件上传系统兼容IE 开始
function load() {
}
//用来添加文件列表的函数
function AddList(rows) {
//根据数组来添加列表
var FileList = $("idFileList"),
oFragment = document.createDocumentFragment();
//用文档碎片保存列表
Each(rows, function (cells) {
var row = document.createElement("tr");
Each(cells, function (o) {
var cell = document.createElement("td");
if (typeof o == "string") {
cell.innerHTML = o;
} else {
cell.appendChild(o);
}
row.appendChild(cell);
});
oFragment.appendChild(row);
})
//ie的table不支持innerHTML所以这样清空table
while (FileList.hasChildNodes()) {
FileList.removeChild(FileList.firstChild);
}
FileList.appendChild(oFragment);
}
//在后台通过window.parent来访问主页面的函数
function Finish(msg, filenames) {
alert(msg);
ReturnValue(filenames);
}
function ReturnValue(filenames) {
parent.close4();
}
function getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]);
return null;
}
//旧文件上传系统兼容IE 结束
</script>
</body>
</html>
后端处理类
File.ashx
<%@ WebHandler Language="c#" Class="File_WebHandler" Debug="true" %>
using System;
using System.Configuration;
using System.IO;
using System.Web;
using DBUtility;
public class File_WebHandler : IHttpHandler
{
private const int UploadFileLimit = 10;//上传文件数量限制
public static string _msg = "上传成功!";//返回信息
//private string _filenames = ""; //返回上传文件名
public void ProcessRequest(HttpContext context)
{
var method = context.Request.QueryString["method"];
switch (method)
{
case "ajaxFileUpload":
ajaxFileUpload(context);
break;
default:
defaultFileUpload(context);
break;
}
}
public bool IsReusable
{
get
{
return false;
}
}
private static void defaultFileUpload(HttpContext context)
{
//context.Response.ContentType = "text/plain";
//context.Request.ContentType = "text/plain";
// string ispostback=context.Request.Form["isPostBack"];
string BillCode = context.Request["BillCode"];
int iTotal = context.Request.Files.Count;
if (iTotal == 0)
{
_msg = "没有数据";
}
else
{
int iCount = 0;
for (int i = 0; i < iTotal; i++)
{
HttpPostedFile file = context.Request.Files[i];
if (file.ContentLength > 0 || !string.IsNullOrEmpty(file.FileName))
{
//创建目录
///生成一个适合的路径存放
string d = DateTime.Now.Year.ToString() + "" + DateTime.Now.Month.ToString() + "" + DateTime.Now.Day.ToString();
string dirPath = "../../html/Flow/file/" + d;
if (!Directory.Exists(HttpContext.Current.Request.MapPath(dirPath)))
{
Directory.CreateDirectory(HttpContext.Current.Request.MapPath(dirPath));
}
string name = Path.GetFileName(file.FileName);//获取输入的文件名字
int i1 = name.LastIndexOf(".");
string newname = name.Substring(0, i1);
//string tempname = newname;
string extname = name.Substring(i1);//获取文件的扩展名
// 以时间命名
newname = DateTime.Now.ToString("yyyyMMddHHmmss");
string filename = newname + extname;
// 重名判断
int icount = 1;
while (true)
{
if (File.Exists(HttpContext.Current.Server.MapPath(dirPath + "/" + filename)))
{
filename = newname + "(" + Convert.ToString(icount) + ")" + extname;
icount++;
}
else
{
break;
}
}
//保存文件
file.SaveAs(HttpContext.Current.Server.MapPath(dirPath + "/" + filename));
// 记录至数据库
string strSql = @"insert into t_attachment (BillCode,AttachmentType,AttachmentName,AttachmentPath,CreateDateTime,Status)
values ('" + BillCode + "','" + extname + "','" + name.Substring(0, i1) + "','" + dirPath + "/" + filename + "','" + DateTime.Now.ToString() + "',1)";
DbHelperSQL.ExecuteSql(strSql);
//这里可以根据实际设置其他限制
if (++iCount > UploadFileLimit)
{
_msg = "超过上传限制:" + UploadFileLimit;
break;
}
}
}
}
context.Response.Write("<script>window.parent.Finish('" + _msg + "','');</script>");
}
private static void ajaxFileUpload(HttpContext context)
{
HttpFileCollection files = context.Request.Files;
string BillCode = context.Request["BillCode"];
int length = int.Parse(context.Request.QueryString["length"] ?? "0");
string msg = string.Empty;
string error = string.Empty;
try
{
if (context.Request.Files.Count > 0)
{
string fileName = VirtualPathUtility.GetDirectory(context.Request.Url.LocalPath);
context.Response.Write("0");
}
else
{
context.Response.Write("3");
}
context.Response.ContentType = "application/json; charset=utf-8";
}
catch (Exception ex)
{
// ExceptionLogging c = new ExceptionLogging("Admin Upload Failed", ex);
// c.ErrorLog(HttpContext.Current.ApplicationInstance.Server.MapPath("~/Logs/"));
}
}
}
效果edge Chrome 火狐等如下
老的IE浏览器也能兼容