Uploadify使用随笔
最近项目使用了Uploadify一个上传插件,感觉的挺好用的。
上传控件:
引用JS
<script src='<% =ResolveUrl("~/JS/Uploadify/jquery.uploadify.js")%>' type="text/javascript"></script>
插件使用方法:
function UploadFY() {
var upload = {
'swf': '../JS/Uploadify/uploadify.swf',
'uploader': '../Ashx/FileOpHandler.ashx?Op=UploadFile&KGuid=' + Kguid + '&dType=SHPY_Files',
'buttonImg': '<% =ResolveUrl("~/JS/Uploadify/licon_001.gif")%>',
'cancelImg': '<% =ResolveUrl("~/JS/Uploadify/cancel.png")%>',
'queueID': Kguid,
'auto': true,
'multi': true,
'height': 22,
'width': 70,
'buttonText': '',
'fileTypeDesc': '系统支持文件', // The description for file types in the browse dialog
'fileTypeExts': '*.doc;*.docx;*.xls;*.xlsx;*.pdf;*.rar;*.gd',
//需要重写的事件
'overrideEvents': ['onSelectError', 'onDialogClose'],
'multi': false, //是否允许多选
'auto': true, //是否允许自动上传
'method': 'GET',
'queueSizeLimit': 300, //同时上传数量
'uploadLimit': 10000, //一次浏览器课上成总数量
'fileSizeLimit': '10MB', //单个文件大小设置
'sizeLimit': 4000000,
'onQueueComplete': function (file) { //所有文件上传完成时触发此事件
},
'onSelect': function (file) {
//$('#fileupload').uploadifySettings('formData', { 'ASPSESSID': ASPSESSID, 'AUTHID': auth });
//alert(formDate);
fileName = file.name;
},
//返回一个错误,选择文件的时候触发
'onSelectError': function (file, errorCode, errorMsg) {
switch (errorCode) {
case -100:
alert("上传的文件数量已经超出系统限制的" + $('#fileupload').uploadify('settings', 'queueSizeLimit') + "个文件!");
return;
case -110:
alert("文件 [" + file.name + "] 大小超出系统限制的10MB大小!");
// alert("文件 [" + file.name + "] 大小超出系统限制的" + $('#fileupload').uploadify('settings', 'fileSizeLimit') + "大小!");
return;
case -120:
alert("文件 [" + file.name + "] 大小超出系统限制的10MB大小!");
return;
case -130:
alert("文件 [" + file.name + "] 类型不正确!");
return;
default:
alert("文件 [" + file.name + "] 文件检查发生错误!");
return;
}
},
//检测FLASH失败调用
'onFallback': function () {
alert("您未安装FLASH控件,无法上传图片!请安装FLASH控件后再试。");
},
'width': 34, //文件选择按钮大小
'height': 22,
'removeCompleted': true,
'removeTimeout': 0.1, //上传完成后自动消失时间/秒
'onQueueComplete': function (file) { //所有文件上传完成时触发此事件
if (fileName.length > 100) {
alert("文件名过长!");
return;
}
$("#hdAttachmentName").val(fileName);
$("#hdAttachmentPath").val('/uploads/SHPY_Files' + '/' + Kguid + '/' + fileName);
$("#<%=DivFileLink.ClientID %>").html('<a href="javascript:void(0)" onclick="Down()" >' + fileName + '</a> <img src="../JS/Uploadify/cancel.png" align="middle" onclick=DeleteFile() />');
}
}
return upload;
}
function LoadUpload() {
$("input[type='file']").each(function () {
$(this).uploadify((UploadFY()))
});
}
function Down() {
document.getElementById('btnDown').click();
}
function DeleteFile() {
$("#hdAttachmentName").val('');
$("#hdAttachmentPath").val('');
$("#<%=DivFileLink.ClientID %>").html('');
//此处可写触发删除文件
}
页面加载的时候调用:
LoadUpload();
FileOpHandler.ashx
上传代码:
private void UploadFile(HttpContext context)
{
try
{
HttpPostedFile file = context.Request.Files["Filedata"];
string KGuid = q(context, "KGuid");
string FileName = file.FileName;
int FileLength = file.ContentLength; ;
string FileType = file.FileName.Substring(file.FileName.LastIndexOf("."));
string CreateUserName = q(context, "CreateUserName");
string CreateUserID = q(context, "CreateUserID");
DateTime CreateDateTime = DateTime.Now;
string uploadPath = context.Server.MapPath("..\\uploads\\" + q(context, "dType") + "\\" + KGuid + "\\");
string FilePath = "..\\uploads\\" + q(context, "dType") + "\\" + KGuid + "\\" + FileName;
if (file != null)
{
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
file.SaveAs(uploadPath + file.FileName);
//生成缩略图
}
context.Response.Write("1");
}
catch
{
context.Response.Write("0");
}
}
private string q(HttpContext context, string str)
{
if (context.Request[str] != null)
return context.Request[str].ToString();
return "";
}
public bool success
{
get;
set;
}
/// <summary>
/// Gets or sets the MSG.
/// </summary>
/// <value>The MSG.</value>
public string msg
{
get;
set;
}
/// <summary>
/// Gets or sets the public key.
/// </summary>
/// <value>The public key.</value>
public object data
{
get;
set;
}
文件下载:
protected void btnDown_Click(object sender, EventArgs e)
{
string filePath = Server.MapPath("../" + hdAttachmentPath.Value);
try
{
FileInfo info = new FileInfo(filePath);
if (!info.Exists)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "message", "$.messager.alert('消息提示', '文件不存在!', 'info');", true);
return;
}
long fileSize = info.Length;
Response.Clear();
Response.ContentType = "application/x-zip-compressed";
Response.AddHeader("Content-Disposition", "attachment;filename=" +HttpUtility.UrlEncode( info.Name));
//不指明Content-Length用Flush的话不会显示下载进度
Response.AddHeader("Content-Length", fileSize.ToString());
Response.TransmitFile(filePath, 0, fileSize);
Response.Flush();
Response.Close();
}
catch (Exception ex)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "message", "$.messager.alert('消息提示', " + ex.Message + ", 'info');", true);
}
}