帶進度條的文件批量上傳插件uploadify


有時項目中需要一個文件批量上傳功能時,個人認為uploadify是快速簡便的解決方案。

先上效果圖:

一. 下載uploadify

從官網下載uploadify的Flash版本(Flash版本免費,另一版本HTML5版本需要付費)

下載地址: http://www.uploadify.com/download/

下載后直接把文件解壓,然后放在項目中

二. 在項目中使用

在頁面中引入:

    <!--引入Jquery-->
    <script src="js/jquery-1.11.3.min.js"></script>
    <!--引入uploadify-->
    <script type="text/javascript" src="uploadify/jquery.uploadify.js"></script>
    <link type="text/css" href="uploadify/uploadify.css" rel="stylesheet" />

完整頁面代碼

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>文件批量上傳Demo</title>
    <!--引入Jquery-->
    <script src="js/jquery-1.11.3.min.js"></script>
    <!--引入uploadify-->
    <script type="text/javascript" src="uploadify/jquery.uploadify.js"></script>
    <link type="text/css" href="uploadify/uploadify.css" rel="stylesheet" />

    <script type="text/javascript">
        $(function () {
            var guid = '<%=Request["guid"] %>';
            var type = '<%=Request["type"] %>';
            if (guid == null || guid == "") {
                guid = newGuid();
            }
            if (type != null) {
                type = type + '/';
            }

            $('#file_upload').uploadify({
                'swf': 'uploadify/uploadify.swf',              //FLash文件路徑
                'buttonText': '瀏  覽',                        //按鈕文本
                'uploader': 'uploadhandler.ashx?guid=' + guid, //處理ASHX頁面
                'formData': { 'folder': 'picture', 'isCover': 1 },         //傳參數
                'queueID': 'fileQueue',                        //隊列的ID
                'queueSizeLimit': 10,                          //隊列最多可上傳文件數量,默認為999
                'auto': false,                                 //選擇文件后是否自動上傳,默認為true
                'multi': true,                                 //是否為多選,默認為true
                'removeCompleted': true,                       //是否完成后移除序列,默認為true
                'fileSizeLimit': '0',                          //單個文件大小,0為無限制,可接受KB,MB,GB等單位的字符串值
                'fileTypeDesc': 'All Files',                   //文件描述
                'fileTypeExts': '*.*',                         //上傳的文件后綴過濾器
                'onQueueComplete': function (queueData) {      //所有隊列完成后事件
                    alert("上傳完畢!");
                },
                'onError': function (event, queueId, fileObj, errorObj) {
                    alert(errorObj.type + "" + errorObj.info);
                },
                'onUploadStart': function (file) {
                },
                'onUploadSuccess': function (file, data, response) {   //一個文件上傳成功后的響應事件處理
                    //var data = $.parseJSON(data);//如果data是json格式
                    //var errMsg = "";
                }

            });
        });

        function newGuid() {
            var guid = "";
            for (var i = 1; i <= 32; i++) {
                var n = Math.floor(Math.random() * 16.0).toString(16);
                guid += n;
                if ((i == 8) || (i == 12) || (i == 16) || (i == 20))
                    guid += "-";
            }
            return guid;
        }

        //執行上傳
        function doUpload() {
            $('#file_upload').uploadify('upload', '*');
        }
    </script>

</head>
<body>
    <form id="form1" runat="server" enctype="multipart/form-data">
        <div id="fileQueue" class="fileQueue"></div>
        <div>
            <input type="file" name="file_upload" id="file_upload" />
            <p>
                <input type="button" class="shortbutton" id="btnUpload" onclick="doUpload()" value="上傳" />
                &nbsp;&nbsp;&nbsp;&nbsp;
                <input type="button" class="shortbutton" id="btnCancelUpload" onclick="$('#file_upload').uploadify('cancel')" value="取消" />
            </p>
            <div id="div_show_files"></div>
        </div>
    </form>
</body>
</html>
View Code

UploadHandler.ashx代碼

using System;
using System.Web;
using System.IO;

public class UploadHandler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Request.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
        context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
        context.Response.Charset = "UTF-8";

        if (context.Request.Files.Count > 0)
        {
            #region 獲取上傳路徑
            string uploadFolder = GetUploadFolder();
            #endregion

            if (System.IO.Directory.Exists(uploadFolder))
            {//如果上傳路徑存在
                HttpPostedFile file = context.Request.Files["Filedata"];
                string filePath = Path.Combine(uploadFolder, file.FileName);
                file.SaveAs(filePath);
                context.Response.Write("0");
            }
            else
            {
                context.Response.Write("2");
            }
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

    /// <summary>
    /// 返回不帶后綴的文件名
    /// </summary>
    /// <param name="fileName"></param>
    /// <returns></returns>
    public static string GetFirstFileName(string fileName)
    {
        return Path.GetFileNameWithoutExtension(fileName);
    }

    /// <summary>
    /// 獲取上傳目錄
    /// </summary>
    /// <returns></returns>
    public static string GetUploadFolder()
    {
        string rootPath = HttpContext.Current.Server.MapPath("~");
        return Path.Combine(rootPath, "test");
    }

}
View Code

Demo下載

三. 延伸和總結

文件上傳.NET默認有大小限制,像IIS限制的30M默認請求大小。如果不想修改IIS,又想突破這個大小限制,比如上傳1GB大小的文件。

這時修改Web.config即可實現

<?xml version="1.0" encoding="utf-8"?>

<!--
  有關如何配置 ASP.NET 應用程序的詳細信息,請訪問
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>

    <system.web>
      <compilation debug="true" targetFramework="4.0" />
      <httpRuntime maxRequestLength="1073741824"/>
    </system.web>

    <!--用於設置文件上傳的最大允許大小(單位:bytes)-->
    <system.webServer>
      <security>
        <requestFiltering>
          <!--修改服務器允許最大長度(1GB)-->
          <requestLimits maxAllowedContentLength="1073741824"/>
        </requestFiltering>
      </security>
    </system.webServer>
  
</configuration>

希望本文對你有幫助。


免責聲明!

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



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