SWFUpload小记

首先,本文需要感谢各位使用SWFUpload上传组件的前辈高人。

下面进入正文。

由于项目需要,普通的文件上传已经不能满足客户的需求。所以,就有了此文。

1、SWF的Demo 在这里可以找到各种脚本文件,而不用去想破头。 

2、google讨论组 在这里可以找到各种问题的解决方案。

3、不断调试。最初通过link方式引入handlers.js,各种事件提示文字会显示乱码,故把整个handlers.js直接放在同一页面上了。

4、进度条、状态条提示文字部分是自己翻译的, 如有需要可自行修改。

代码上传有异常,只能直接粘进来了。标红的部分需要与否有待考证!部分源码


 

AddAttachments2.aspx

<%@ Page Language="C#" AutoEventWireup="true" Codebehind="AddAttachments2.aspx.cs"
    Inherits="gxjt.AddAttachments2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<% Server.ScriptTimeout = 9999999; %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>SWFUpload</title>
    <link href="/swfupload/default.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="/swfupload/swfupload.js"></script>
    <script type="text/javascript" src="/swfupload/swfupload.queue.js"></script>
    <script type="text/javascript" src="/swfupload/fileprogress.js"></script>
    <script type="text/javascript">
   
    var iTime = ""; //intial time
    var Timeleft = ""; //time left
    //roundNumber found via google
    function roundNumber(num, dec) {
        var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
        return result;
    }
    //minsec created by Daem0nX (03.29.08)
    function minsec(time, tempTime) {
        var ztime;
        if (time == "m") {
           ztime = Math.floor(tempTime/60);
           if (ztime < 10) {
            ztime = "0" + ztime; 
           }
        } else if (time == "s") {
           ztime = Math.ceil(tempTime % 60);
           if (ztime < 10) {
            ztime = "0" + ztime; 
           }
        } else {
           ztime = "minsec error...";
        }
        return ztime;
    }
    function fileQueued(file) {
   try {
   var progress = new FileProgress(file, this.customSettings.progressTarget);
   progress.setStatus("待上传...");
   progress.toggleCancel(true, this);
   } catch (ex) {
   this.debug(ex);
   }
    }
    function fileQueueError(file, errorCode, message) {
   try {
   if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
   alert("尝试添加的文件过多.\n" + (message === 0 ? "文件大小超过限制." : "你只能选择 " + (message > 1 ? "最多 " + message + " 个文件." : "每个文件.")));
   return;
   }
   var progress = new FileProgress(file, this.customSettings.progressTarget);
   progress.setError();
   progress.toggleCancel(false);
   switch (errorCode) {
   case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
   progress.setStatus("文件过大.");
   this.debug("错误代码: 文件过大, 文件名: " + file.name + ", 大小: " + file.size + ", 错误信息: " + message);
   break;
   case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
   progress.setStatus("不能上传0字节文件.");
   this.debug("错误代码: 0字节文件, 文件名: " + file.name + ", 大小: " + file.size + ", 错误信息: " + message);
   break;
   case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
   progress.setStatus("无效的文件类型.");
   this.debug("错误代码: 无效的文件类型, 文件名: " + file.name + ", 大小: " + file.size + ", 错误信息: " + message);
   break;
   default:
   if (file !== null) {
   progress.setStatus("未知错误");
   }
   this.debug("错误代码: " + errorCode + ", 文件名: " + file.name + ", 大小: " + file.size + ", 错误信息: " + message);
   break;
   }
   } catch (ex) {
            this.debug(ex);
        }
    }
    function fileDialogComplete(numFilesSelected, numFilesQueued) {
   try {
   if (numFilesSelected > 0) {
   document.getElementById(this.customSettings.cancelButtonId).disabled = false;
   }
   
   /* I want auto start the upload and I can do that here */
   this.startUpload();
   } catch (ex)  {
            this.debug(ex);
   }
    }
    function uploadStart(file) {
   try {
   /* I don't want to do any file validation or anything,  I'll just update the UI and
   return true to indicate that the upload should start.
   It's important to update the UI here because in Linux no uploadProgress events are called. The best
   we can do is say we are uploading.
    */
           var currentTime = new Date()
           iTime = currentTime;
           //Set Timeleft to estimating
           Timeleft = "计算中...";
            
           var progress = new FileProgress(file, this.customSettings.progressTarget);
           progress.setStatus("Uploading...");
           progress.toggleCancel(true, this);
   }
   catch (ex) {}
   
   return true;
    }
    function uploadProgress(file, bytesLoaded, bytesTotal) {
        try {
           var currentTime = new Date()
           var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
           var progress = new FileProgress(file, this.customSettings.progressTarget);
           progress.setProgress(percent);
           var tempTime = 0;
           //rndfilesize = round file size  
           var rndfilesize = roundNumber(((file.size/1024)/1024),1);
           //uploaded = how much has been uploaded
           var uploaded = roundNumber(((bytesLoaded/1024)/1024),1);
           //uTime = uploadTime (time spent uploading)
           var uTime = (Math.ceil(currentTime-iTime)/1000);
           //uSpeed = uploadSpeed (40 kB/s)
           var uSpeed = Math.floor(roundNumber(((bytesLoaded/uTime)/1024),2));
           //tempTime = store time for following functions
           var tempTime = uTime;
           //uploadTime in min:sec
           uTime = "用时" + minsec("m", tempTime) + "分:" + minsec("s", tempTime) + "秒";
           //tempTime = reassign val
           tempTime = roundNumber(((((bytesTotal-bytesLoaded)/uSpeed)/60)/10),2);
           if (tempTime != "Infinity") {
            if (tempTime > 0) {
             //if greater than 0
             //Timeleft in min:sec
             Timeleft = minsec("m", tempTime) + "分:" + minsec("s", tempTime) + '秒';
            } else {
             Timeleft = "计算中...";
            }
           } else {
            Timeleft = "计算中...";
           }
          
           progress.setStatus('<b><font color=red>' +uploaded + '</font></b>/' + rndfilesize + ' MB,上传速度: <b><font color=red>' + uSpeed + ' </font></b>KB/秒; 剩余时间: <b><font color=red>' + Timeleft + '</font></b>; 总进度 <b><font color=red>' + percent + '%</font></b>');
            
        } catch (ex) {
           this.debug(ex);
        }
    }
    function uploadSuccess(file, serverData) {
        try {
           var currentTime = new Date()
           var progress = new FileProgress(file, this.customSettings.progressTarget);
           progress.setComplete();
           //Calculate upload time
           var cTime = (Math.ceil(currentTime-iTime)/1000);
           var zmin = 0;
           var zsec = 0;
           zmin = Math.floor(cTime/60);
           if (zmin < 10) {
            zmin = "0" + zmin; 
           }
           zsec = Math.ceil(cTime % 60);
           if (zsec < 10) {
            zsec = "0" + zsec; 
           }
           //Show how long the upload took
           progress.setStatus("上传完成,用时:<b><font color=red> " + zmin + "分:" + zsec + '秒</font></b>');
           progress.toggleCancel(false);
        } catch (ex) {
           this.debug(ex);
        }
    }
    function uploadError(file, errorCode, message) {
   try {
   var progress = new FileProgress(file, this.customSettings.progressTarget);
   progress.setError();
   progress.toggleCancel(false);
   switch (errorCode) {
   case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
   progress.setStatus("上传错误: " + message);
   this.debug("错误代码: HTTP 错误, 文件名: " + file.name + ", 错误信息: " + message);
   break;
   case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
   progress.setStatus("上传失败.");
   this.debug("错误代码: 上传失败, 文件名: " + file.name + ", 大小: " + file.size + ", 错误信息: " + message);
   break;
   case SWFUpload.UPLOAD_ERROR.IO_ERROR:
   progress.setStatus("服务器IO错误");
   this.debug("错误代码: IO 错误, 文件名: " + file.name + ", 错误代码: " + message);
   break;
   case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
   progress.setStatus("安全错误");
   this.debug("错误代码: 安全错误, 文件名: " + file.name + ", 错误代码: " + message);
   break;
   case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
   progress.setStatus("超出上传大小限制.");
   this.debug("错误代码: 超出上传大小限制, 文件名: " + file.name + ", 大小: " + file.size + ", 错误信息: " + message);
   break;
   case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
   progress.setStatus("验证失败.  跳过上传.");
   this.debug("错误代码: 文件验证失败, 文件名: " + file.name + ", 大小: " + file.size + ", 错误信息: " + message);
   break;
   case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
   // If there aren't any files left (they were all cancelled) disable the cancel button
   if (this.getStats().files_queued === 0) {
   document.getElementById(this.customSettings.cancelButtonId).disabled = true;
   }
   progress.setStatus("已取消");
   progress.setCancelled();
   break;
   case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
   progress.setStatus("已停止");
   break;
   default:
   progress.setStatus("未知错误: " + errorCode);
   this.debug("错误代码: " + errorCode + ", 文件名: " + file.name + ", 大小: " + file.size + ", 错误信息: " + message);
   break;
   }
   } catch (ex) {
            this.debug(ex);
        }
    }
    function uploadComplete(file) {
   if (this.getStats().files_queued === 0) {
   document.getElementById(this.customSettings.cancelButtonId).disabled = true;
   }
    }
    // This event comes from the Queue Plugin
    function queueComplete(numFilesUploaded) {
   var status = document.getElementById("divStatus");
   status.innerHTML = "已上传文件数:" + numFilesUploaded + " .";
    }
    </script>
    <script type="text/javascript">
var swfu;
window.onload = function() {
var settings = {
flash_url : "swfupload/swfupload.swf",
upload_url: 'AttachmentUpload.aspx?ModelCode=<%=Request["ModelCode"] %>&id=<%=Request["id"] %>&htno=<%=Request["htno"] %>',
post_params: {"PHPSESSID" : ""},
file_size_limit : "200 MB",
file_types : "*.*",
file_types_description : "所有文件",
file_upload_limit : 100,
file_queue_limit : 0,
custom_settings : {
progressTarget : "fsUploadProgress",
cancelButtonId : "btnCancel"
},
debug: false,
// Button settings
button_image_url: "images/TestImageNoText_65x29.png",
button_width: "150",
button_height: "29",
button_placeholder_id: "spanButtonPlaceHolder",
button_text: '<span class="theFont">选择文件(可多选)</span>',
button_text_style: ".theFont { font-size: 14; }",
button_text_left_padding: 12,
button_text_top_padding: 3,
// The event handler functions are defined in handlers.js
file_queued_handler : fileQueued,
file_queue_error_handler : fileQueueError,
file_dialog_complete_handler : fileDialogComplete,
upload_start_handler : uploadStart,
upload_progress_handler : uploadProgress,
upload_error_handler : uploadError,
upload_success_handler : uploadSuccess,
upload_complete_handler : uploadComplete,
queue_complete_handler : queueComplete // Queue plugin event
};
swfu = new SWFUpload(settings);
    };
    </script>
</head>
<body>
    <form id="form1" enctype="multipart/form-data">
        <div id="content">
            <div class="fieldset flash" id="fsUploadProgress">
                <span class="legend">上传队列</span>
            </div>
            <div id="divStatus">
                已上传文件数:0</div>
            <div>
                <span id="spanButtonPlaceHolder"></span>
                <input id="btnCancel" type="button" value="全部取消" onclick="swfu.cancelQueue();" disabled="disabled"
                    style="margin-left: 2px; font-size: 8pt; height: 29px;" />
            </div>
        </div>
    </form>
</body>
</html>

 Attachments.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Collections.Generic;
using Webpub;

namespace gxjt
{
    
public partial class AttachmentUpload : System.Web.UI.Page
    {
        gxjt.BLL.Attachments bllAttachments 
= new gxjt.BLL.Attachments();
        gxjt.Model.Attachments modelAttachments 
= new gxjt.Model.Attachments();
        gxjt.BLL.Base_Model bllModel 
= new gxjt.BLL.Base_Model();
        
public string ModelCode = string.Empty;
        
public int MoudleID;
        
public string ProjCode = string.Empty;

        
protected void Page_Load(object sender, EventArgs e)
        {
            
if (Request["id"!= null && Request["id"].ToString() != "")
            {
                MoudleID 
= int.Parse(Request["id"].ToString());
                ProjCode 
= ((pubSession)Session["pubSession"]).ProjCode;
                ModelCode 
= Request["ModelCode"!= null ? HttpUtility.UrlDecode(Request["ModelCode"].ToString()) : "Unknown";
            }

            
try
            {
                SaveDoc(ModelCode, MoudleID);
                Response.StatusCode 
= 200;
            }
            
catch
            {
                
// If any kind of error occurs return a 500 Internal Server error
                Response.StatusCode = 500;
                Response.Write(
"An error occured");
                Response.End();
            }
            
finally
            {
                
// Clean up
                Response.End();
            }
        }

        
protected void SaveDoc(string Moudle, int MoudleID)
        {
            
string filePath = "";
            
string fileExt = String.Empty;

            string sFileName = "";
            
string strDir = String.Empty;
            GetDir(Moudle, 
ref strDir);
            
string CurDir = Server.MapPath("/Attachments/" + ProjCode + "/" + strDir);
            
string sSaveFullFileName = "";

            
//创建不存在的目录
            if (!Directory.Exists(CurDir))
                Directory.CreateDirectory(CurDir);

            
// Get the data
            HttpPostedFile UploadFile = Request.Files["Filedata"];


            filePath 
= UploadFile.FileName;

            sFileName 
= System.IO.Path.GetFileNameWithoutExtension(filePath);
            fileExt 
= System.IO.Path.GetExtension(filePath);
            sFileName 
+= "(" + Moudle + "_" + MoudleID.ToString() + ")" + fileExt;

            
if (filePath != "")
            {
                sSaveFullFileName 
= CurDir + "\\" + sFileName;

                modelAttachments.ProjectCode 
= ((pubSession)Session["pubSession"]).ProjCode;
                modelAttachments.ModelCode 
= Moudle;
                modelAttachments.ModelTableID 
= MoudleID;
                modelAttachments.FilesName 
= sFileName;
                modelAttachments.UploadDate 
= System.DateTime.Now;
                modelAttachments.UploadUserName 
= ((pubSession)Session["pubSession"]).UserName;
                modelAttachments.DocumentType 
= 1;
                modelAttachments.htno 
= Request["htno"!= null ? Request["htno"].ToString() + "," : "";
                bllAttachments.Add(modelAttachments);

                UploadFile.SaveAs(sSaveFullFileName);

                ExtAspNet.PageContext.RegisterStartupScript(
"refreshGrid();");
            }
        }

        
private void GetDir(string strModelCode, ref string strDir)
        {
            
int ilength = 0;
            
while (ilength < strModelCode.Length)
            {
                strDir 
+= bllModel.GetEnglishName(strModelCode.Substring(0, ilength + 2)) + "/";
                ilength 
+= 2;
            }
        }

    }

}
 

posted on 2011-05-31 17:58  飘渺冰血  阅读(1555)  评论(0编辑  收藏  举报