Jquery Uploadify插件使用方法


cnblogs的第一篇博文,放假前的最后一天班。

因為放完假要做一個小項目,年前先拆分下各個部分,其中有上傳文件這一塊。在網上找了jquery uplodify插件的使用方法,於是照着其他博文嘗試。最終簡單的功能是實現了,不過也費了不少勁,汗顏。做下總結。


 

1. 主要引入的文件

Uploadify.css 該文件包括插件所用樣式
Uploadify.swf 進度條
Cancel.png 顯示在進度條上的取消按鈕
Jquery.js(v1.4.4) js庫文件

Jquery_uploadify.js(v2.1.4)

Swfobject.js(v2.2)

主要文件

                           

 

2. Uploadify插件主要參數(參考http://www.uploadify.com/documentation/

uploadify:function(options) {
jQuery(this).each(function(){
var settings = jQuery.extend({
id : jQuery(this).attr('id'), // The ID of the object being Uploadified
uploader : 'uploadify.swf', // The path to the uploadify swf file
script : 'uploadify.php', // The path to the uploadify backend upload script
expressInstall : null, // The path to the express install swf file
folder : '', // The path to the upload folder
height : 30, // The height of the flash button
width : 120, // The width of the flash button
cancelImg : 'cancel.png', // The path to the cancel image for the default file queue item container
wmode : 'opaque', // The wmode of the flash file
scriptAccess : 'sameDomain', // Set to "always" to allow script access across domains
fileDataName : 'Filedata', // The name of the file collection object in the backend upload script
method : 'POST', // The method for sending variables to the backend upload script
queueSizeLimit : 999, // The maximum size of the file queue
simUploadLimit : 1, // The number of simultaneous uploads allowed
queueID : false, // The optional ID of the queue container
displayData : 'percentage', // Set to "speed" to show the upload speed in the default queue item
removeCompleted : true, // Set to true if you want the queue items to be removed when a file is done uploading
onInit : function() {}, // Function to run when uploadify is initialized
onSelect : function() {}, // Function to run when a file is selected
onSelectOnce : function() {}, // Function to run once when files are added to the queue
onQueueFull : function() {}, // Function to run when the queue reaches capacity
onCheck : function() {}, // Function to run when script checks for duplicate files on the server
onCancel : function() {}, // Function to run when an item is cleared from the queue
onClearQueue : function() {}, // Function to run when the queue is manually cleared
onError : function() {}, // Function to run when an upload item returns an error
onProgress : function() {}, // Function to run each time the upload progress is updated
onComplete : function() {}, // Function to run when an upload is completed
onAllComplete : function() {} // Function to run when all uploads are completed
}

 

3. 使用該插件主要添加的兩個文件

  a) Default.aspx  :用於顯示和配置上述參數

  b)Uploadfile.ashx :后台處理上傳文件(.cs、.aspx.cs等等文件都可以做后台文件,個人感覺ashx比aspx安全,比.cs方便)

4. 注意點

  a)Default.aspx中要有<div id="fileQueue"></div>,顯示進度條用

  b)web.config中<system.web>內添加節點

  <httpRuntime maxRequestLength="1000"/>,maxRequestLength 單位為kb(應該是kb,沒有查資料,只是自己調試)。選擇上傳的文件大小不能超過這個值

5. 簡單實現

  a)Select按鈕瀏覽要上傳的文件, Upload Files上傳按鍵

        

  b)點擊select,選擇文件后

  

  c) 上傳成功

      

  d)上傳失敗

     


Default.aspx代碼:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="JqueryUpLoadFile.Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="css/uploadify.css" rel="Stylesheet" />

<script type="text/javascript" src="scripts/jquery.js"></script>

<script type="text/javascript" src="scripts/jquery_uploadify.js"></script>

<script type="text/javascript" src="scripts/swfobject.js"></script>

<style type="text/css">
.div_uploaddiv a
{
color: #0072BC;
text-decoration: none;
}
.divMain
{
background-color: #FFFFFF;
width: 350x;
margin: 100px 0 0 300px;
margin-bottom: 10px;
}
</style>

<script type="text/javascript">
$(document).ready(function() {
$("#file_upload").uploadify({
'fileDataName': 'Filedata',
'uploader': '/Flash/uploadify.swf',
'script': '/uploadfile.ashx', //后台處理
'cancelImg': '/images/cancel.png', //單個取消按鈕
//'buttonImg': '/images/acurapartswarehouse.com.png',
//'folder': '/uploadfile', //文件夾
'queueID': 'fileQueue', //文件隊列
'auto': false, //true:選擇文件后自動開始上傳;false:手動觸發
'multi': true, //多文件上傳,
'simUploadLimit': '4', //The number of simultaneous uploads allowed
'fileExt': '*.doc;*.pdf;*.rar;*.zip;*.7z;*.chm;*.jpg;*.gif;*.png;*.bak', //.jpg,.bmp,.gif,.png,.doc,.pdf,.rar,.zip,.7z,可上傳文件
'fileDesc': '*.doc;*.pdf;*.rar;*.zip;*.7z;*.chm;*.jpg;*.gif;*.png;*.bak', //顯示的文件類型
'buttonText': 'select',
'width': '100',
'height': '32',
'removeCompleted': false,
'sizeLimit': '100000000', //大小限制,100M
'queueSizeLimit': 3, //The maximum size of the file queue
//'onError': function(event, queueID, fileObj, errorObj) {
// alert('error ' + errorObj.type);
//},//返回錯誤信息
//'onComplete': function (event, queueID, fileObj, response, data) {
// alert(respone);
//},
'onComplete': function(event, queueID, fileObj, response, data) {
//alert("成功上傳,平均速率:"+data.speed+"kb/s");
if (response == "0")
$("#haveupfile").append("<p style='color:#f00'>上傳" + fileObj.name + "失敗!</p>");
else if (response == "1")
$("#haveupfile").append("<p style='color:#f00'>" + fileObj.name + "文件格式錯誤!</p>");
},
'onAllComplete': function(event, data) {
$("#haveupfile").append("<p>成功上傳<b>" + data.filesUploaded + "個文件</b></p>");
}
});
});

</script>

</head>
<body>
<div class="divMain">
<div id="fileQueue">
</div>
<input type="file" name="uploadify" id="file_upload" />
<div class="div_uploaddiv">
<a id="uploadtag" href="javascript:$('#file_upload').uploadifyUpload()">Upload Files</a>
</div>
<div id="haveupfile">
</div>
</div>
</body>
</html>

后台文件上傳代碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Configuration;

namespace JqueryUpLoadFile
{
/// <summary>
/// uploadfile 的摘要說明
/// </summary>
public class uploadfile : IHttpHandler
{
public string extensionlimit = ".doc,.pdf,.rar,.zip,.doc,.7z,.chm,.jpg,.gif,.png,.bak";//用逗號隔開,小寫..
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Charset = "utf-8";
string fileFullName = string.Empty;
string uploadPath = string.Empty;
string fileContain = string.Empty;
try
{
HttpPostedFile postedFile = context.Request.Files["Filedata"];
uploadPath = context.Request.PhysicalApplicationPath + ConfigurationManager.AppSettings["filePath"];
fileFullName = uploadPath + Path.GetFileName(postedFile.FileName);

if (postedFile != null)
{
fileContain =Path.GetExtension(postedFile.FileName).ToLower();
if (extensionlimit.Contains(fileContain))
{
if (fileFullName != "")
{
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
}
postedFile.SaveAs(fileFullName);
//下面這句代碼缺少的話,上傳成功后上傳隊列的顯示不會自動消失
//返回網絡路徑
context.Response.Write(fileFullName);
}
else
{
context.Response.Write("1");//擴展驗證失敗
}
}
else
{
context.Response.Write("0");//驗證失敗
}
}
catch (Exception ex)
{
context.Response.Write(ex.Message);
}
}

public bool IsReusable
{
get
{
return false;
}
}
}
}

 


 

寫的有些累贅;添加表格后竟然不會刪。。還得靠F12調樣式,各位笑看。

先祝各位新年好,好運來,身體健康,闔家幸福

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM