完整uploadify批量上传文件插件使用
1.首先准备uploadify的js文件,网上一搜一大堆
2.上传页面UpFilePage.aspx
关键代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>上传文件</title>
<link href="/jquery.uploadify/uploadify.css" rel="stylesheet" />
<script type="text/javascript" src="/jquery.uploadify/jquery-1.8.3.min.js"></script>
<script src="/jquery.uploadify/swfobject.js" charset="utf-8"></script>
<script src="/jquery.uploadify/jquery.uploadify.v2.1.0.js"></script>
<style type="text/css">
#fileSave { padding-left:5px; padding-right:5px;}
#fileSave .uploadifyQueueItem{ width:530px;}
#fileQueue { padding-left:5px; padding-right:5px;}
#fileQueue .uploadifyQueueItem { width:530px;}
#uploadifyUploader { position:absolute; opacity:0;}
.uploadify-button{ height: 30px; line-height: 30px; width: 109px; text-align:center; border:0px; margin-bottom:5px; background:#ff6600; color:#fff;}
.cancel a { background:url(/jquery.uploadify/cancel.png) no-repeat center center; display:inline-block; width:16px; height:16px;}
</style>
</head>
<body>
<form id="form1" runat="server">
<div style="margin:10px;">
<div style="height:38px;" >
<div>
<input type="file" name="uploadify" id="uploadify" />
<div id="uploadify-button" class="uploadify-button"><span class="uploadify-button-text">添加文件</span></div>
</div>
<div id="fileQueue"></div>
<div id="fileSave">
<%=GetFile() %>
</div>
</div>
</div>
</form>
<script type="text/javascript">
var fileCount = 0;
$(document).ready(function () {
fileCount = $("#fileSave>div.uploadifyQueueItem").length;
$("input[name='radPhone']:eq(0)").attr("checked", "checked");
$("#uploadify").uploadify({
'uploader': '/jquery.uploadify/uploadify.swf',//uploadify.swf 文件的相对路径
'script': '/jquery.uploadify/uploadHandler.ashx',//处理文件的程序
//'cancelImg': '/Scripts/jquery.uploadify/cancel.png',//取消图片
//'folder': 'upfiles',//上传文件存放的目录
'queueID': 'fileQueue',//文件队列的ID
//'fileDesc': '*.flv;*.mp4;*.wmv;*.avi;*.3gp;*.mpg;*.ppt;*.pptx',//上传格式限制
//'fileExt': '*.flv;*.mp4;*.wmv;*.avi;*.3gp;*.mpg;*.ppt;*.pptx',//上传格式限制
"queueSizeLimit": "5",//当允许多文件生成时,设置选择文件的个数
'auto': true,//设置为true当选择文件后就直接上传了
'multi': true,//设置为true时可以上传多个文件
"fileDataName": "imgFile",//设置一个名字,在服务器处理程序中根据该名字来取上传文件的数据
"sizeLimit": "5242880",//上传文件的大小限制,以字节为单位
"simUploadLimit": "1",// 允许同时上传的个数 默认值:1
"onSelect": function (e, queueId, fileObj) {
fileCount = $("#fileSave>div.uploadifyQueueItem").length;
var less = 5 - fileCount;
if (less <= 0) {
layer.msg("最多只能上传5个附件");
$("#a_upload").attr("href", "javascript:");
return false;
} else {
$("#a_upload").attr("href", "javascript:$('#uploadify').uploadifyUpload()");
return true;
}
},
"onComplete": function () {
$.ajax({
type: "post",
url: "/UploadAction/UploadHandler.ashx",
data: { operate: "GetFile" },
async: false,
success: function (objdata) {
$("#fileSave").html(objdata);
fileCount = $("#fileSave>div.uploadifyQueueItem").length;
var less = 5 - fileCount;
if (less <= 0) {
$("#a_upload").attr("href", "javascript:");
$("#fileQueue").html("");
return false;
} else {
$("#a_upload").attr("href", "javascript:$('#uploadify').uploadifyUpload()");
return true;
}
}
});
},
"onCancel": function () {
fileCount = $("#fileSave>div.uploadifyQueueItem").length;
var less = 5 - fileCount;
if (less <= 0) {
$("#a_upload").attr("href", "javascript:");
return false;
} else {
$("#a_upload").attr("href", "javascript:$('#uploadify').uploadifyUpload()");
return true;
}
},
});
});
function deleteFile(path) {
$.ajax({
type: "post",
url: "/UploadAction/UploadHandler.ashx",
data: { operate: "deleteFile", file: path },
success: function (objdata) {
$("#fileSave").html(objdata);
fileCount = $("#fileSave>div.uploadifyQueueItem").length;
var less = 5 - fileCount;
if (less <= 0) {
$("#a_upload").attr("href", "javascript:");
} else
$("#a_upload").attr("href", "javascript:$('#uploadify').uploadifyUpload()");
}
});
}
</script>
</body>
</html>
后台的GetFile()方法:
/// <summary>
/// 获取cookie附件信息
/// </summary>
/// <returns></returns>
protected string GetFile()
{
#region 获取cookie附件信息
StringBuilder strHtml = new StringBuilder();
HttpCookie fileCookie = Request.Cookies["FileCookie"];
if (fileCookie != null)
{
string[] fileArray = new string[1];
if (fileCookie.Value.Contains("|"))
fileArray = fileCookie.Value.Split('|');
else
fileArray[0] = fileCookie.Value;
foreach (string objFile in fileArray)
{
if (!string.IsNullOrEmpty(objFile) && objFile.Contains(","))
{
string[] file = objFile.Split(',');
strHtml.Append(@"<div class='uploadifyQueueItem'>");
strHtml.Append(@"<div class='cancel'>");
strHtml.Append("<a href='javascript:deleteFile(\"" + file[1] + "\")'></a>");
//strHtml.Append(@"<img src='/Scripts/jquery.uploadify/cancel.png' border='0'>");
strHtml.Append(@"</div>");
strHtml.Append(@"<span class='fileName'>" + HttpUtility.UrlDecode(file[0]) + "</span><span class='percentage'> - 100%</span><div class='uploadifyProgress'>");
strHtml.Append(@"<div class='uploadifyProgressBar' style='width: 100%;'>");
strHtml.Append(@"</div>");
strHtml.Append(@"</div>");
strHtml.Append(@"</div>");
}
}
}
return strHtml.ToString();
#endregion
}
3.UploadAction文件夹下的一般处理程序:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string operate = context.Request["operate"];
if (operate == "deleteFile")
{
#region 删除文件附件信息
//获取文件路径
string filePath = context.Server.MapPath(context.Request["file"]);
//判断文件是否存在
if (File.Exists(filePath))
File.Delete(filePath);//删除文件
//获取附件cookie信息
HttpCookie fileCookie = context.Request.Cookies["FileCookie"];
string[] fileArray = new string[1];
if (fileCookie != null)
{
filePath = filePath.Remove(0, filePath.IndexOf("upfiles")).Replace("\\", "/");
if (fileCookie.Value.Contains("|"))
fileArray = fileCookie.Value.Split('|');
else
fileArray[0] = fileCookie.Value;
string strFile = "";
for (int i = 0; i < fileArray.Length; i++)
{
if (!fileArray[i].Contains(filePath))
strFile += fileArray[i] + "|";
}
if (strFile.Contains("|"))
strFile = strFile.Remove(strFile.Length - 1);
fileCookie.Value = strFile;
fileCookie.Expires = DateTime.Now.AddDays(1);
fileCookie.HttpOnly = true;
context.Response.AppendCookie(fileCookie);
StringBuilder strHtml = new StringBuilder();
if (fileCookie.Value.Contains("|"))
fileArray = fileCookie.Value.Split('|');
else
fileArray[0] = fileCookie.Value;
foreach (string objFile in fileArray)
{
if (!string.IsNullOrEmpty(objFile) && objFile.Contains(","))
{
string[] file = objFile.Split(',');
strHtml.Append(@"<div class='uploadifyQueueItem'>");
strHtml.Append(@"<div class='cancel'>");
strHtml.Append("<a href='javascript:deleteFile(\"" + file[1] + "\")'></a>");
//strHtml.Append(@"<img src='/Scripts/jquery.uploadify-v2.1.0/cancel.png' border='0'>");
strHtml.Append(@"</div>");
strHtml.Append(@"<span class='fileName'>" + HttpUtility.UrlDecode(file[0]) + "</span><span class='percentage'> - 100%</span><div class='uploadifyProgress'>");
strHtml.Append(@"<div class='uploadifyProgressBar' style='width: 100%;'>");
strHtml.Append(@"</div>");
strHtml.Append(@"</div>");
strHtml.Append(@"</div>");
}
}
context.Response.Write(strHtml.ToString());
}
#endregion
}
else if (operate == "GetFile")
{
#region 获取上传的附件并展示
StringBuilder strHtml = new StringBuilder();
HttpCookie fileCookie = context.Request.Cookies["FileCookie"];
if (fileCookie != null)
{
string[] fileArray = new string[1];
if (fileCookie.Value.Contains("|"))
fileArray = fileCookie.Value.Split('|');
else
fileArray[0] = fileCookie.Value;
foreach (string objFile in fileArray)
{
if (!string.IsNullOrEmpty(objFile) && objFile.Contains(","))
{
string[] file = objFile.Split(',');
strHtml.Append(@"<div class='uploadifyQueueItem'>");
strHtml.Append(@"<div class='cancel'>");
strHtml.Append("<a href='javascript:deleteFile(\"" + file[1] + "\")'>");
//strHtml.Append(@"<img src='/Scripts/jquery.uploadify-v2.1.0/cancel.png' border='0'></a>");
strHtml.Append(@"</div>");
strHtml.Append(@"<span class='fileName'>" + HttpUtility.UrlDecode(file[0]) + "</span><span class='percentage'> - 100%</span><div class='uploadifyProgress'>");
strHtml.Append(@"<div class='uploadifyProgressBar' style='width: 100%;'>");
strHtml.Append(@"</div>");
strHtml.Append(@"</div>");
strHtml.Append(@"</div>");
}
}
}
context.Response.Write(strHtml.ToString());
#endregion
}
}
4.上传文件uploadHandler.ashx一般处理程序代码,文件上传路径可以根据剧情需要自由设定:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
HttpCookie fileCookie = context.Request.Cookies["FileCookie"];
if (fileCookie != null)
{
string[] fileArray = new string[1];
if (fileCookie.Value.Contains("|"))
fileArray = fileCookie.Value.Split('|');
if (fileArray.Length >= 5)
return;
}
else
{
fileCookie = new HttpCookie("FileCookie");
fileCookie.Value = "";
context.Response.Cookies.Add(fileCookie);
}
String aspxUrl = context.Request.Path.Substring(0, context.Request.Path.LastIndexOf("/") + 1);
//文件保存目录路径
String savePath = "/upfiles/";
//文件保存目录URL
String saveUrl = "/upfiles/";
//if (context.Request.Cookies["Member"] != null)
//{
// savePath += context.Request.Cookies["Member"]["MemberId"] + "/";
// saveUrl += context.Request.Cookies["Member"]["MemberId"] + "/";
//}
string Member = Guid.NewGuid().ToString().Trim().Replace("-", "");
savePath += Member + "/";
saveUrl += Member + "/";
//定义允许上传的文件扩展名
/*Hashtable extTable = new Hashtable();
extTable.Add("image", "gif,jpg,jpeg,png,bmp");
extTable.Add("flash", "swf,flv");
extTable.Add("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,mp4");
extTable.Add("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2,swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb,mp4,wps");*/
//最大文件大小
int maxSize = 5242880;
HttpPostedFile imgFile = context.Request.Files["imgFile"];
/*if (imgFile == null)
{
showError("请选择文件。");
}*/
String dirPath = context.Server.MapPath(savePath);
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
//showError("上传目录不存在。");
}
String dirName = context.Request.QueryString["dir"];
if (String.IsNullOrEmpty(dirName))
{
dirName = "file";
}
/*if (!extTable.ContainsKey(dirName))
{
showError("目录名不正确。");
}*/
String fileName = imgFile.FileName;
String fileExt = Path.GetExtension(fileName).ToLower();
/*if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1)
{
showError("上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[dirName]) + "格式。");
}
if (dirName.Contains("image"))
{
if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
{
showError("上传文件超过5M大小限制。");
}
}*/
//创建文件夹
dirPath += dirName + "/";
saveUrl += dirName + "/";
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
String ymd = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
dirPath += ymd + "/";
saveUrl += ymd + "/";
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
String filePath = dirPath + newFileName;
imgFile.SaveAs(filePath);
String fileUrl = saveUrl + newFileName;
/*Hashtable hash = new Hashtable();
hash["error"] = 0;
hash["url"] = fileUrl;
context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
context.Response.Write(JsonMapper.ToJson(hash));
context.Response.End();*/
if (fileCookie != null)
{
string strFile = fileCookie.Value;
if (!string.IsNullOrEmpty(strFile))
strFile = strFile + "|" + HttpUtility.UrlEncode(fileName) + "," + fileUrl;
else
strFile = HttpUtility.UrlEncode(fileName) + "," + fileUrl;
fileCookie.Value = strFile;
fileCookie.Expires = DateTime.Now.AddDays(1);
fileCookie.HttpOnly = true;
context.Response.AppendCookie(fileCookie);
}
context.Response.Write("1");
context.Response.End();
}
5.所有代码敲完OK,可以收获成果了:
完整uploadify批量上传文件插件使用的更多相关文章
- uploadify+批量上传文件+java
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding= ...
- Uploadify 上传文件插件详解
Uploadify 上传文件插件详解 Uploadify是JQuery的一个上传插件,实现的效果非常不错,带进度显示.不过官方提供的实例时php版本的,本文将详细介绍Uploadify在Aspnet中 ...
- 项目一:第四天 1、快递员的条件分页查询-noSession,条件查询 2、快递员删除(逻辑删除) 3、基于Apache POI实现批量导入区域数据 a)Jquery OCUpload上传文件插件使用 b)Apache POI读取excel文件数据
1. 快递员的条件分页查询-noSession,条件查询 2. 快递员删除(逻辑删除) 3. 基于Apache POI实现批量导入区域数据 a) Jquery OCUpload上传文件插件使用 b) ...
- 使用 jquery 的 上传文件插件 uploadify 3.1 配合 java 来做一个简单的文件上次功能。并且在界面上有radio 的选择内容也要上传
使用 jquery 的 上传文件插件 uploadify 3.1 配合 java 来做一个简单的文件上次功能.并且在界面上有radio 的选择内容也要上传 uploadify 插件的 下载和文档地址 ...
- uploadify 上传文件插件
今天在项目中要用到文件上传功能时,想借助Jquery方式来实现,于是想到用uploadify插件来实现.不经意间在网上看到了一遍关于这个插件的用法,写的很好.在这里就分享给大家,希望对大家有帮助.以下 ...
- 不带插件 ,自己写js,实现批量上传文件及进度显示
今天接受项目中要完成文件批量上传文件而且还要显示上传进度,一开始觉得这个应该不是很麻烦,当我在做的时候遇到了很多问题,很头疼啊. 不过看了别人写的代码,自己也测试过,发现网上好多都存在一些问题,并不是 ...
- mvc中使用uploadify批量上传的应用
网上找了很多资料都没有发现一个好用.可以用的uploadify批量上传的应用,这里通过官方和自己的一些项目需要整理了一个出来. 希望能帮助到需要的人. 效果图:
- Linux命令之rz - 批量上传文件,简单易用(转载)
用途说明 rz命令能够批量上传文件,当然也可上传单个文件啦.使用的协议是古老的ZMODEM协议,尽管协议古老,但毫不影响的简单易用的特性.一般情 况我们要上传文件到Linux系统,要么使用ftp(还得 ...
- 转 Android网络编程之使用HttpClient批量上传文件 MultipartEntityBuilder
请尊重他人的劳动成果,转载请注明出处:Android网络编程之使用HttpClient批量上传文件 http://www.tuicool.com/articles/Y7reYb 我曾在<Andr ...
随机推荐
- 瞎写的树dfs序
这里枚举了树的DFS序来解决树上问题的多个板子,自己最好多看看. ↓改↓ ↓求↓ 点 点 ————————>>>这个就算了 点 树 简单, BIT 点 链 重点! 树 树 简单, 线 ...
- P2764 [网络流24题]最小路径覆盖问题[最大流]
地址 这题有个转化,求最少的链覆盖→即求最少联通块. 设联通块个数$x$个,选的边数$y$,点数$n$个 那么有 $y=n-x$ 即 $x=n-y$ 而n是不变的,目标就是在保证每个点入度.出度 ...
- ACM学习历程—HDU1716 排列2(dfs && set容器)
Description Ray又对数字的列产生了兴趣: 现有四张卡片,用这四张卡片能排列出很多不同的4位数,要求按从小到大的顺序输出这些4位数. Input 每组数据占一行,代表四张卡片上的数字( ...
- ESFramework Demo -- P2P通信Demo(附源码)
现在我们将在ESFramework Demo -- 文件传送Demo 的基础上,使用ESPlus提供的第四个武器,为其增加P2P通信的功能.在阅读本文之前,请务必先掌握ESFramework 开发手册 ...
- 查看MySql数据库物理文件存放位置
查找数据库文件位置使用命令 show global variables like "%datadir%";
- Python 通用日志模块
import os base_dir=os.path.dirname(os.path.dirname(__file__)) base_db=os.path.join(base_dir,'db') ba ...
- 演讲:对 2000 多亿条数据做一次 group by 需要多久?
http://2017.qconbeijing.com/presentation/646?utm_source=weibo&utm_medium=infoq&utm_campaign= ...
- WPF学习系列之二 (依赖项属性)
依赖属性;(dependency property) 它是专门针对WPF创建的,但是WPF库中的依赖项属性都使用普通的.NET属性过程进行了包装.从而可能通过常规的方式使用它们,即使使用他们的代码不 ...
- SetCapture到底是什么?
函数功能:该函数在属于当前线程的指定窗口里设置鼠标捕获.一旦窗口捕获了鼠标,所有鼠标输入都针对该窗口,无论光标是否在窗口的边界内.同一时刻只能有一个窗口捕获鼠标.如果鼠标光标在另一个线程创建的窗口上, ...
- POJ - 2031 Building a Space Station 三维球点生成树Kruskal
Building a Space Station You are a member of the space station engineering team, and are assigned a ...