jQuery.uploadify文件上傳組件實例講解
1、jquery.uploadify簡介
在ASP.NET中上傳的控件有很多,比如.NET自帶的FileUpload,以及SWFUpload,Uploadify等等,尤其后面兩個控件的用戶體驗比較好,無刷新,帶上傳進度等等。在最近的短信平臺開發(fā)中,使用Uploadify進行文件上傳。
Uploadify官網(wǎng)地址是:http://www.uploadify.com/ 可滿足項目開發(fā)需求。

下載地址:http://www.uploadify.com/wp-content/uploads/files/uploadify.zip 版本信息如下:
解壓之后,目錄結(jié)構(gòu)如下(不在詳細(xì)解釋):

2、使用流程
下載的程序是PHP示例,由于項目使用的是asp.net mvc,使用uploadify可分以下步驟:
•(1)加入uploadify js類庫(把uploadify相關(guān)js類庫引用到項目的相關(guān)位置,比如放到scripts目錄)
•(2)對uploadify二次進行封裝,滿足項目調(diào)用
•(3)編寫文件上傳處理方法
•(4)頁面引用相關(guān)類庫并編寫上傳腳本
2.1 對uploadify二次進行封裝
針對uploadify調(diào)用進行js類庫封裝,滿足項目使用:
//轉(zhuǎn)換成key=value&key=value格式
tx.toParam = function (dto) {
return jQuery.param(dto);
}
//設(shè)置上傳文件
tx.uploadify = function (divId, options, action) {
if (options == undefined && action == undefined) {
$('#' + divId).uploadify("upload");
return;
}
if (options == undefined) {
abp.message.warn("請輸入?yún)?shù)配置");
return;
}
var fileexts = options.fileexts;
if (fileexts == undefined || fileexts.length <= 0) {
abp.message.warn("要選擇文件的擴展名不能為空");
return;
}
$('#' + divId).uploadify({
uploader: '/files/upload?r=' + Math.random()
+ "&fileexts=" + encodeURIComponent(fileexts)
+ "&" + (options !== undefined ? tx.toParam(options.params) : ""), // 服務(wù)器端處理地址
swf: '/Scripts/uploadify/uploadify.swf', // 上傳使用的 Flash
width: 60, // 按鈕的寬度
height: 23, // 按鈕的高度
buttonText: "選擇文件", // 按鈕上的文字
buttonCursor: 'hand', // 按鈕的鼠標(biāo)圖標(biāo)
fileObjName: 'Filedata', // 上傳參數(shù)名稱
fileTypeExts: fileexts, // 擴展名
fileTypeDesc: "請選擇文件", // 文件說明
fileDesc: '不超過200M的',
sizeLimit: 204800000, //允許上傳的文件大小(kb) 此為2M
auto: false, // 選擇之后,自動開始上傳
multi: true, // 是否支持同時上傳多個文件
queueSizeLimit: 1, // 允許多文件上傳的時候,同時上傳文件的個數(shù)
onSelectOnce: function (event, data) { //在單文件或多文件上傳時,選擇文件時觸發(fā)
//event 事件對象(the event object)
//data 選擇的操作信息
//data.filesSelected 選擇文件操作中選中的文件數(shù)量
},
onUploadStart: function (file) {
//file:將要上載的文件對象
ShowBusy();
},
onUploadComplete: function (file) {
//file:上傳或返回一個錯誤的文件對象。
},
onUploadSuccess: function (file, data, response) {
//file:成功上傳的文件對象
//data:服務(wù)器端腳本返回的數(shù)據(jù)(任何由文件響應(yīng)的任何東西)
//response:服務(wù)器返回的響應(yīng)是否真的成功或錯誤,如果沒有響應(yīng)。如果返回false,這successtimeout期權(quán)到期后的反應(yīng)真是假設(shè)。
if (action !== undefined) {
action(JSON.parse(data));
}
ClearBusy();
},
onUploadError: function (file, errorCode, errorMsg, errorString) {
//file:上傳的文件對象
//errorCode:返回的錯誤代碼
//errorMsg:返回的錯誤消息
//errorString:包含錯誤的所有細(xì)節(jié)的可讀的錯誤信息
if (action !== undefined) {
if (action !== undefined) {
action({
result: errorCode,
message: errorMsg,
filename: "",
fileext: ""
});
}
}
ClearBusy();
}
});
}
2.2 文件上傳處理
使用MVC特性,要登錄之后才能進行文件上傳:
using System;
using System.IO;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace TxSms.Web.Controllers
{
/// <summary>
/// 文件上傳管理
/// </summary>
[Authorize]
public class FilesController : TxSmsControllerBase
{
private static string jsonResult = "{0}\"result\":{1},\"message\":\"{2}\",\"filename\":\"{3}\",\"fileext\":\"{4}\"{5}";
/// <summary>
/// 文件上傳頁面
/// </summary>
/// <returns></returns>
[Authorize]
public ActionResult Index()
{
return View();
}
/// <summary>
/// 上傳文件
/// </summary>
/// <param name="filedata"></param>
/// <returns></returns>
[Authorize]
public ActionResult Upload(HttpPostedFileBase filedata)
{
// 如果沒有上傳文件
if (filedata == null || filedata.FileName.IsNullOrEmpty() || filedata.ContentLength == 0)
{
return new JsonStringResult(string.Format(jsonResult, "{", -1, "", "", "", "}"));
}
string parmPath = Request.QueryString["path"];
string parmGetzipfile = Request.QueryString["getzipfile"];
if (parmGetzipfile.IsNullOrEmpty())
{
parmGetzipfile = "0";
}
// 保存到 ~/uploads 文件夾中,名稱不變
string time = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string fileext = Path.GetExtension(filedata.FileName);
string filename = time + fileext;
string virtualPath = parmPath.IsNullOrEmpty()
? $"~/uploads/"
: $"~/uploads/{parmPath}/";
string actualPath = Server.MapPath(virtualPath);
if (!Directory.Exists(actualPath))
{
Directory.CreateDirectory(Server.MapPath(virtualPath));
}
// 文件系統(tǒng)不能使用虛擬路徑
var destFile = virtualPath + filename;
string path = Server.MapPath(destFile);
filedata.SaveAs(path);
bool iszip = fileext != null && (fileext.Equals(".zip", StringComparison.OrdinalIgnoreCase) && parmGetzipfile.Equals("1"));
if (iszip)
{
var virtualPathZip = virtualPath + time + "/";
string actualPathZip = Server.MapPath(virtualPathZip);
if (!Directory.Exists(actualPathZip))
{
Directory.CreateDirectory(actualPathZip);
}
destFile = fileext = "";
//第一步驟,解壓
TxSmsZipHelper.UnZipFile(path, actualPathZip);
//第二步驟,獲取excel文件,如果沒有獲取到,則拋出異常
//獲得目錄信息
var dir = new DirectoryInfo(actualPathZip);
//獲得目錄文件列表
var files = dir.GetFiles();
foreach (FileInfo fileName in files)
{
//var ext = Path.GetExtension(fileName.Name).ToLower();
//if (ext == ".xls" || ext == ".xlsx")
//{
// destFile = Path.Combine(fileName.DirectoryName, fileName.Name);
// break;
//}
destFile = virtualPathZip + fileName.Name;
fileext = Path.GetExtension(fileName.Name);
break;
}
}
return new JsonStringResult(string.Format(jsonResult, "{", 0, "上傳成功", destFile, fileext.ToLower(), "}"));
}
public class JsonStringResult : ContentResult
{
public JsonStringResult(string json)
{
Content = json;
ContentType = "application/json";
}
}
}
}
文件上傳路徑:/files/upload
2.3 頁面調(diào)用
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="/Content/themes/base/uploadify/uploadify.css" rel="stylesheet"/>
<script src="/Scripts/jquery-2.1.4.min.js"></script>
<script src="/Scripts/uploadify/jquery.uploadify.min.js"></script>
<script type="text/javascript">
$(function () {
var ASPSESSID = '3iupfg2udk4m5hyzfj5ydlso';
var auth = '';
//初始化
tx.uploadify('uploadify'
,
{ //參數(shù)配置
fileexts: "*.jpg;*.png;*.zip", //要選擇文件的擴展名,多個用;分割
//formData: { ASPSESSID: ASPSESSID, AUTHID: auth },
params: { //參數(shù)
path: 'files',//上傳路徑,允許為空
getzipfile: 1 //解壓zip文件,并獲取文件 0:不解壓獲取,1:解壓獲取
}
}
, function (data) { //回調(diào)函數(shù)
//data.result:0 表示成功,其他表示錯誤
//data.message:信息
//data.filename:文件名稱
//data.fileext:文件擴展
console.log(data.result);
console.log(data.message);
console.log(data.filename);
console.log(data.fileext);
});
$("#btnUpload").click(function () {
tx.uploadify('uploadify'); //開始上傳
});
});
</script>
</head>
<body>
<div style="margin: 40px;">
<div id="uploadify"></div>
<button id="btnUpload">開始上傳</button>
</div>
</body>
</html>
允許程序,界面如下:
選擇文件—>開始上傳:
ok,到此已經(jīng)完成。
3、http 302解決方案
很懷疑二八原則,很快就出現(xiàn)了。同事用firefox進行測試,遇到如下提示:
查找大量資料,發(fā)下是Upload方法認(rèn)證的問題,去掉[Authorize]屬性標(biāo)簽即可,代碼修改如下:
using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
namespace TxSms.Web.Controllers
{
/// <summary>
/// 文件上傳管理
/// </summary>
//[Authorize]
public class FilesController : TxSmsControllerBase
{
private static string jsonResult = "{0}\"result\":{1},\"message\":\"{2}\",\"filename\":\"{3}\",\"fileext\":\"{4}\"{5}";
/// <summary>
/// 文件上傳頁面
/// </summary>
/// <returns></returns>
[Authorize]
public ActionResult Index()
{
return View();
}
/// <summary>
/// 上傳文件
/// </summary>
/// <param name="filedata"></param>
/// <returns></returns>
//[Authorize]
public ActionResult Upload(HttpPostedFileBase filedata)
{
//加入認(rèn)證信息
if (this.LoginUser == null)
{
return new JsonStringResult(string.Format(jsonResult, "{", -1, "抱歉,未登錄,不允許上傳", "", "", "}"));
}
// 如果沒有上傳文件
if (filedata == null || filedata.FileName.IsNullOrEmpty() || filedata.ContentLength == 0)
{
return new JsonStringResult(string.Format(jsonResult, "{", -2, "無上傳文件", "", "", "}"));
}
string parmPath = Request.QueryString["path"];
string parmGetzipfile = Request.QueryString["getzipfile"];
if (parmGetzipfile.IsNullOrEmpty())
{
parmGetzipfile = "0";
}
// 保存到 ~/uploads 文件夾中,名稱不變
string time = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string fileext = Path.GetExtension(filedata.FileName);
string filename = time + fileext;
string virtualPath = parmPath.IsNullOrEmpty()
? $"~/uploads/"
: $"~/uploads/{parmPath}/";
string actualPath = Server.MapPath(virtualPath);
if (!Directory.Exists(actualPath))
{
Directory.CreateDirectory(Server.MapPath(virtualPath));
}
// 文件系統(tǒng)不能使用虛擬路徑
var destFile = virtualPath + filename;
string path = Server.MapPath(destFile);
filedata.SaveAs(path);
bool iszip = fileext != null && (fileext.Equals(".zip", StringComparison.OrdinalIgnoreCase) && parmGetzipfile.Equals("1"));
if (iszip)
{
var virtualPathZip = virtualPath + time + "/";
string actualPathZip = Server.MapPath(virtualPathZip);
if (!Directory.Exists(actualPathZip))
{
Directory.CreateDirectory(actualPathZip);
}
destFile = fileext = "";
//第一步驟,解壓
TxSmsZipHelper.UnZipFile(path, actualPathZip);
//第二步驟,獲取excel文件,如果沒有獲取到,則拋出異常
//獲得目錄信息
var dir = new DirectoryInfo(actualPathZip);
//獲得目錄文件列表
var files = dir.GetFiles();
foreach (FileInfo fileName in files)
{
//var ext = Path.GetExtension(fileName.Name).ToLower();
//if (ext == ".xls" || ext == ".xlsx")
//{
// destFile = Path.Combine(fileName.DirectoryName, fileName.Name);
// break;
//}
destFile = virtualPathZip + fileName.Name;
fileext = Path.GetExtension(fileName.Name);
break;
}
}
return new JsonStringResult(string.Format(jsonResult, "{", 0, "上傳成功", destFile, fileext.ToLower(), "}"));
}
public class JsonStringResult : ContentResult
{
public JsonStringResult(string json)
{
Content = json;
ContentType = "application/json";
}
}
}
}
再次用firefox測試如下:


4、注意事項
1、封裝的js類庫適合單文件上傳
2、upload里面的登錄認(rèn)證是通過判斷當(dāng)前賬號信息是否為null
3、本項目使用的abp框架,有興趣的可以去了解下:http://www.aspnetboilerplate.com/
以上所述是小編給大家介紹的jQuery.uploadify文件上傳組件實例講解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
- JQuery.uploadify 上傳文件插件的使用詳解 for ASP.NET
- php+jQuery.uploadify實現(xiàn)文件上傳教程
- firefox瀏覽器用jquery.uploadify插件上傳時報HTTP 302錯誤
- 圖片上傳插件jquery.uploadify詳解
- jquery.uploadify插件在chrome瀏覽器頻繁崩潰解決方法
- jQuery.Uploadify插件實現(xiàn)帶進度條的批量上傳功能
- SpringMVC文件上傳 多文件上傳實例
- jquery.form.js框架實現(xiàn)文件上傳功能案例解析(springmvc)
- 使用jQuery.form.js/springmvc框架實現(xiàn)文件上傳功能
- SpringMVC + jquery.uploadify實現(xiàn)上傳文件功能
相關(guān)文章
基于jQuery實現(xiàn)交互體驗社會化分享代碼附源碼下載
基于jQuery實現(xiàn)交互體驗社會化分享代碼附源碼下載。這是一款鼠標(biāo)點擊分享按鈕向右滑出騰訊微博,新浪微博,QQ空間,豆瓣,微信,二維碼分享等分享平臺,本段代碼比較實用,需要的朋友參考下吧2016-01-01
jQuery僅用3行代碼實現(xiàn)的顯示與隱藏功能完整實例
這篇文章主要介紹了jQuery僅用3行代碼實現(xiàn)的顯示與隱藏功能,以完整實例形式分析了jQuery實現(xiàn)鼠標(biāo)響應(yīng)及頁面元素屬性變換的相關(guān)技巧,需要的朋友可以參考下2015-10-10
用jQuery技術(shù)實現(xiàn)Tab頁界面之二
這個tab頁是把數(shù)據(jù)全部取回來再顯示,所以沒有數(shù)據(jù)緩存的特點。但是因為數(shù)據(jù)全部是顯示的html代碼,所以對搜索引擎是友好的,也許對seo有好處。2009-09-09
基于jquery實現(xiàn)的鼠標(biāo)滑過按鈕改變背景圖片
基于jquery實現(xiàn)的鼠標(biāo)滑過按鈕改變背景圖片,發(fā)現(xiàn)用CSS用時IE6不兼容,所以就用見JQ實現(xiàn)。2011-07-07
基于jQuery的圖片大小自動適應(yīng)實現(xiàn)代碼
這個和以前弄的圖片遠(yuǎn)處放大有許多相同的地方,比如圖片預(yù)加載、有限容器顯示無限大圖片。2010-11-11
jquery實現(xiàn)點擊彈出可放大居中及關(guān)閉的對話框(附demo源碼下載)
這篇文章主要介紹了jquery實現(xiàn)點擊彈出可放大居中及關(guān)閉的對話框,具有可拖動、放大、居中及關(guān)閉等功能,提供了2種對話框模式供讀者選擇,并附帶demo源碼供讀者下載參考,需要的朋友可以參考下2016-05-05
jQuery實現(xiàn)導(dǎo)航滾動到指定內(nèi)容效果完整實例【附demo源碼下載】
這篇文章主要介紹了jQuery實現(xiàn)導(dǎo)航滾動到指定內(nèi)容效果,結(jié)合完整實例形式分析了頁面元素屬性動態(tài)變換操作相關(guān)技巧,涉及jQuery插件jquery.scrollto.js的使用,并附帶demo源碼下載供讀者下載參考,需要的朋友可以參考下2016-09-09






