首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

swfupload事例

2012-12-28 
swfupload例子%@ page contentTypetext/htmlcharsetUTF-8%%double perMaxSize 1.5//单个文件允

swfupload例子
<%@ page contentType="text/html;charset=UTF-8"%>
<%
    double perMaxSize = 1.5;//单个文件允许的max大小
    String sizeUnit = "MB";//perMaxSize数据对应的单位
    String ext = "*.jpg;*.jpeg;*.gif";//允许上传的文件类型
    //文件上传提交的目标页面
    StringBuffer uploadUrl = new StringBuffer("http://");
    uploadUrl.append(request.getHeader("Host"));
    uploadUrl.append(request.getContextPath());
    uploadUrl.append("/admin/swfuploadexample/UploadFileExampleSubmit.jsp教程");
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>批量相片上传</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="css教程/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript教程" src="js/swfupload.js"></script>
<script type="text/javascript" src="js/swfupload.swfobject.js"></script>
<script type="text/javascript" src="js/swfupload.queue.js"></script>
<script type="text/javascript" src="js/fileprogress.js"></script>
<script type="text/javascript" src="js/handlers.js"></script>
<script type="text/javascript">
var swfu;
SWFUpload.onload = function () {
    var settings = {
        flash_url : "js/swfupload.swf",
        upload_url: "<%=uploadUrl.toString()%>",
        post_params: {
            "user_id" : "stephen830",
            "pass_id" : "123456"
        },
        file_size_limit : "<%=perMaxSize%> <%=sizeUnit%>",
        file_types : "<%=ext%>",
        file_types_description : "<%=ext%>",
        file_upload_limit : 100,
        file_queue_limit : 0,
        custom_settings : {
            progressTarget : "fsUploadProgress",
            cancelButtonId : "btnCancel",
            uploadButtonId : "btnUpload",
            myFileListTarget : "idFileList"
        },
        debug: false,
        auto_upload:false,
        // Button Settings
        button_image_url : "images/XPButtonUploadText_61x22.png",    // Relative to the SWF file
        button_placeholder_id : "spanButtonPlaceholder",
        button_width: 61,
        button_height: 22,
        // The event handler functions are defined in handlers.js
        swfupload_loaded_handler : swfUploadLoaded,
        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
       
        // SWFObject settings
        minimum_flash_version : "9.0.28",
        swfupload_pre_load_handler : swfUploadPreLoad,
        swfupload_load_failed_handler : swfUploadLoadFailed
    };
    swfu = new SWFUpload(settings);
}
-----------------------------------------------
</script>
</head>
<body bgcolor="#FCFCFC" topmargin="0px" leftmargin="10px" rightmargin="10px" scroll="yes">
<table width="100%" cellspacing="4" cellpadding="4" border="0" bgcolor="#FCFCFC">
    <tr>
    <td cellspacing="4" cellpadding="4" border="0" bgcolor="#FCFCFC">
    <tr>
    <td align="right"></td>
    </tr>
    </table>
<div id="content">
    <form id="form1" action="UploadFileExampleSubmit.jsp" method="post" enctype="multipart/form-data">
        <table width="90%" cellspacing="0" cellpadding="0" border="0"><tr><td>
        <span id="spanButtonPlaceholder"></span>
        <input id="btnUpload" type="button" value="上传相片" />
        <input id="btnCancel" type="button" value="取消全部上传" disabled="disabled" /></td>
        </tr></table>
        <table id="idFileList" style="visibility: hidden;"></div>
        <noscript style="display: block; margin: 10px 25px; padding: 10px 15px;">
            很抱歉,相片上传界面无法载入,请将浏览器设置成支持JavaScript。
        </noscript>
        <div id="divLoadingContent" style="background-color: #FFFF66; border-top: solid 4px #FF9966; border-bottom: solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px; display: none;">
            相片上传界面正在载入,请稍后...
        </div>
        <div id="divLongLoading" style="background-color: #FFFF66; border-top: solid 4px #FF9966; border-bottom: solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px; display: none;">
            相片上传界面载入失败,请确保浏览器已经开启对JavaScript的支持,并且已经安装可以工作的Flash插件版本。
        </div>
        <div id="divAlternateContent" style="background-color: #FFFF66; border-top: solid 4px #FF9966; border-bottom: solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px; display: none;">
            很抱歉,相片上传界面无法载入,请安装或者升级您的Flash插件。
            请访问: <a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" target="_blank">Adobe网站</a> 获取最新的Flash插件。
        </div>
    </form>
</div>
</td></tr></table>
</body>
</html>
----------------
UploadFileExample.jsp对应的处理页面 --> UploadFileExampleSubmit.jsp
(1)请确保已经看完我的另一篇文章(上传下载组件SmartUpload使用方法 http://stephen830.javaeye.com/admin/blogs/255010),先搞好这个才能开始下面的操作 
(2)写一个对应上传方法类,com.soft4j.bo.PhotoMgr.java,其中的方法就是文章下面提到的public static String fileUpload(SmartUpload su,PageContext pageContext) throws Exception {...}
<%@ page contentType="text/html;charset=UTF-8"%><%@ page import="com.soft4j.httpupload4j.SmartUpload"%><%@ page import="com.soft4j.bo.PhotoMgr"%><%  
    String pageErrorInfo = null;  
    SmartUpload su = null;  
    try{  
        su = new SmartUpload();  
        su.initialize(pageContext);  
        su.upload();  
        pageErrorInfo = PhotoMgr.fileUpload(su,pageContext);  
        if(pageErrorInfo==null){  
            out.print("successed");  
        }  
    }catch(Exception e){  
        pageErrorInfo = e.getMessage();  
    }finally{  
        su = null;  
        if(pageErrorInfo!=null){  
            out.print(pageErrorInfo);  
        }  
    }  
%>
<%@ page contentType="text/html;charset=UTF-8"%><%@ page import="com.soft4j.httpupload4j.SmartUpload"%><%@ page import="com.soft4j.bo.PhotoMgr"%><%
    String pageErrorInfo = null;
    SmartUpload su = null;
    try{
        su = new SmartUpload();
        su.initialize(pageContext);
        su.upload();
        pageErrorInfo = PhotoMgr.fileUpload(su,pageContext);
        if(pageErrorInfo==null){
            out.print("successed");
        }
    }catch(Exception e){
        pageErrorInfo = e.getMessage();
    }finally{
        su = null;
        if(pageErrorInfo!=null){
            out.print(pageErrorInfo);
        }
    }
%>
--------------------
第3步 准备后台的文件上传功能。也就是上面文件[UploadFileExampleSubmit.jsp]中用到的[PhotoMgr.fileUpload(su,pageContext)]方法
Java代码
/** 
     * 文件上传方法. 
     * @param su 
     * @param pageContext 
     * @return 
     * @throws Exception 
     */ 
    public static String fileUpload(SmartUpload su,PageContext pageContext) throws Exception {  
        com.soft4j.httpupload4j.File suFile = null;  
        int fileCount = 0;  
        try {  
            //获取传递过来的参数  
            String userId = su.getRequest().getParameter("user_id");  
            String passId = su.getRequest().getParameter("pass_id");  
 
            String fileExt = "";  
            int fileSize = 0;  
            String AllowedExtensions = ",jpg,jpeg,gif,";//允许上传的文件类型  
            double maxFileSize = 1.5*1024;//单文件最大大小,单位KB  
            //校验文件类型和大小  
            for (int i=0; i<su.getFiles().getCount();i++) {  
                suFile = su.getFiles().getFile(i);  
                if (suFile.isMissing())  
                    continue;  
                //校验文件大小  
                fileSize = suFile.getSize()/1024;//字节转换成KB  
                if(fileSize==0) fileSize=1;  
                if(maxFileSize<fileSize) throw new Exception("单个上传相片的容量不能超过["+maxFileSize+"KB]");  
      
                //校验文件类型  
                if (suFile.getFileExt() == null 
                        || "".equals(suFile.getFileExt())) {  
                    fileExt = ",,";  
                } else {  
                    fileExt = "," + suFile.getFileExt().toLowerCase() + ",";  
                }  
                if (!"".equals(AllowedExtensions)  
                        && AllowedExtensions.indexOf(fileExt) == -1) {  
                    throw new Exception("您上传的文件[" + suFile.getFileName()  
                            + "]的类型为系统禁止上传的文件类型,不能上传!");  
                }  
                fileCount++;  
            }  
-----------------------
if (fileCount==0) throw new Exception("请选择上传的文件");  
            //准备保存文件  
            String filePath="D:\tomcat\webapps教程\test\photo";//这里填写项目中存放上传文件的物理路径  
            for (int i=0; i<su.getFiles().getCount();i++) {  
                suFile = su.getFiles().getFile(i);  
                suFile.saveAs(filePath+suFile.getFileName(),SmartUpload.SAVE_PHYSICAL);//保存文件  
            }  
            //成功返回null  
            return null;  
        } finally {  
            //  
        }  
    }
/**
     * 文件上传方法.
     * @param su
     * @param pageContext
     * @return
     * @throws Exception
     */
    public static String fileUpload(SmartUpload su,PageContext pageContext) throws Exception {
        com.soft4j.httpupload4j.File suFile = null;
        int fileCount = 0;
        try {
            //获取传递过来的参数
            String userId = su.getRequest().getParameter("user_id");
            String passId = su.getRequest().getParameter("pass_id");
            String fileExt = "";
            int fileSize = 0;
            String AllowedExtensions = ",jpg,jpeg,gif,";//允许上传的文件类型
            double maxFileSize = 1.5*1024;//单文件最大大小,单位KB
            //校验文件类型和大小
            for (int i=0; i<su.getFiles().getCount();i++) {
                suFile = su.getFiles().getFile(i);
                if (suFile.isMissing())
                    continue;
                //校验文件大小
                fileSize = suFile.getSize()/1024;//字节转换成KB
                if(fileSize==0) fileSize=1;
                if(maxFileSize<fileSize) throw new Exception("单个上传相片的容量不能超过["+maxFileSize+"KB]");
   
                //校验文件类型
                if (suFile.getFileExt() == null
                        || "".equals(suFile.getFileExt())) {
                    fileExt = ",,";
                } else {
                    fileExt = "," + suFile.getFileExt().toLowerCase() + ",";
                }
                if (!"".equals(AllowedExtensions)
                        && AllowedExtensions.indexOf(fileExt) == -1) {
                    throw new Exception("您上传的文件[" + suFile.getFileName()
                            + "]的类型为系统禁止上传的文件类型,不能上传!");
                }
                fileCount++;
            }
            if (fileCount==0) throw new Exception("请选择上传的文件");
            //准备保存文件
            String filePath="D:\tomcat\webapps\test\photo";//这里填写项目中存放上传文件的物理路径
            for (int i=0; i<su.getFiles().getCount();i++) {
                suFile = su.getFiles().getFile(i);
                suFile.saveAs(filePath+suFile.getFileName(),SmartUpload.SAVE_PHYSICAL);//保存文件
            }
            //成功返回null
            return null;
        } finally {
            //
        }
    }
----------------
关于jsp页面和java方法我不做过多的说明了,应该已经比较清楚了。
本文自发布后,受到了很多朋友的关注,也为不少的朋友提供了帮助,我很高兴。 
下面将朋友们遇到的一些问题作汇总后需要注意的一些地方列了出来:
<1> 功能实现需要flash插件支持。 
flash版本为 flash 9.0.124 或者 flash 10.0.12.36 版本(这是最新的flash10插件). 如果不是的话,可以去flash官网 http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash 进行在线安装。

<2> UploadFileExample.jsp 中的 upload_url参数设置。 
参数需要使用 http://....../UploadFileExampleSubmit.jsp 这样的完整路径.
<3> 关于获取参数 post_params中的参数值。 
post_params: {"user_id" : "stephen830","pass_id" : "123456"} 中的参数,不能使用普通的request.getParameter("")方法来获取, 
而必须用你的上传方法对应的特定方法来获取,比如,我这里用smartupload,则获取方法就是String userId = su.getRequest().getParameter("user_id");
<4> 上传后不管成功还是失败,都需要有返回值。 
这个返回值将传递到对应js中。返回值在UploadFileExampleSubmit.jsp中设置,成功则 out.print("successed"); 失败则 out.print(pageErrorInfo);//pageErrorInfo为错误信息。
该返回值将传递给js目录下的handlers.js文件,具体的方法是 function uploadSuccess(file, serverData) {...} 。
有些朋友的上传成功后out.print("successed"); 发现js收到的"successed"前面会有隐藏字符,遇到这种情况可以更改function uploadSuccess(file, serverData) {...} 中的 
var isSuccess = (serverData.indexOf("successed")==0?true:false); 
改为 
var isSuccess = (serverData.indexOf("successed")>-1?true:false); 
就可以了。
<5> 附件中增加一个完整的测试功能例子。 
附件名 PROJECT_swfupload.zip 下载
附录:swfupload 文件批量上传压缩包 swfupload.zip(支持最新的flash10插件) (附件中没有java类,请自己准备1个java类,将上面的方法复制进去)
为方便了解和调试功能,在附件中增加了一个完整的工程Example,附件名(PROJECT_swfupload.zip),大家可以直接使用来测试功能。

热点排行