uploadify-v3.1 java 实例

来源:互联网 发布:9wifi九维网络官网下载 编辑:程序博客网 时间:2024/05/22 02:07

upLoad.jsp

<%@ page language="java" pageEncoding="UTF-8" errorPage="error.jsp"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <style>
     #uploader{
      position:relative;
     }
     #uploader_queue{
      position:absolute;
      width:600px;
      left:200px;
      top:0;
     }
    </style>
    <title>My JSP 'upLoad.jsp' starting page</title>
    <link type="text/css" rel="stylesheet" href="<%=basePath%>js/plugins/uploadify/uploadify.css"/>
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <script type="text/javascript" src="<%=basePath%>js/jquery-1.7.2.min.js"></script>
 <script type="text/javascript" src="<%=basePath%>js/plugins/uploadify/jquery.uploadify-3.1.min.js"></script>
 <script>
  $(function() {
      $("#file_upload").uploadify({
       'auto' : false,
       'method' : "get",
       'formData' : {'folder' : 'file'},
          'height' : 30,
          'swf' : '<%=basePath%>js/plugins/uploadify/uploadify.swf', // flash
          'uploader' : '<%=basePath%>uploadify', // 数据处理url
          'width' : 120,
          'fileTypeDesc' : '只能是gif...',
          'fileTypeExts' : '*.gif',
          'fileSizeLimit' : '500KB',
          'buttonText' : '选择文件',
          'uploadLimit' : 5,
          'successTimeout' : 5,
          'requeueErrors' : false,
          'removeTimeout' : 10,
          'removeCompleted' : false,
          'queueSizeLimit' :10,
          'queueID'  : 'uploader_queue',
          'progressData' : 'speed',
          'onInit' : function (){},
       // 单个文件上传成功时的处理函数
       'onUploadSuccess' : function(file, data, response){
     $("#uploader_view").append('<img height="60" alt="" src="upload/source/'+ data + '"/>');
    },
          'onQueueComplete' : function(queueData) {
     $('#uploader_msg').html(queueData.uploadsSuccessful + ' files were successfully uploaded.');
    }     
      });
  });
 </script>
  </head>
  <body>
    <a href="<%=basePath%>upload">This is my JSP page. </a><br>
 <div id="uploader">
  <p><input type="file" name="file_upload" id="file_upload" /></p>
  <a href="javascript:$('#file_upload').uploadify('upload','*')">上传</a>&nbsp;
        <a href="javascript:$('#file_upload').uploadify('stop')">取消上传</a>
        <div id="uploader_queue"></div>
        <div id="uploader_msg"></div>
  <div id="uploader_view"></div>
 </div>
  </body>
</html>

UpLoadify.java

package com.test.test;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UpLoadify extends HttpServlet{

 /**
  * 文件上传
  */
 private static final long serialVersionUID = 2384326745121073713L;
 
 @Override
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  System.out.println("-------------------UpLoadify-doGet");
  System.out.println("-------------------QueryString::::" + request.getQueryString());
  doPost(request, response);
 }
 
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  System.out.println("-------------------UpLoadify-doPost");
  System.out.println("-------------------QueryString::::" + request.getQueryString());
  if(request.getParameter("folder")==null||request.getParameter("folder")==""){
   System.out.println("-------------------request.getParameter('folder')::::" + request.getParameter("folder") + " then return");
   return;
  }
  response.setContentType("text/html");
  response.setCharacterEncoding("UTF-8");
  String path = this.getServletContext().getRealPath("/");
  String fileD = request.getParameter("folder");
  String sourcePath = path + "upload/source/";
  path = path + "upload/" + fileD + "/";
  System.out.println("-------------------UpLoadify-path::::" + path);
  File folder = new File(path);
  File sourceFolder = new File(sourcePath);
  if (!folder.exists()) {
   //文件夹不存在则创建
   System.out.println("-------------------UpLoadify::::" + "创建文件夹" + fileD);
   folder.mkdirs();
  }
  if (!sourceFolder.exists()) {
   //文件夹不存在则创建
   System.out.println("-------------------UpLoadify::::" + "创建文件夹source");
   sourceFolder.mkdirs();
  }
  ServletFileUpload sfu = new ServletFileUpload(new DiskFileItemFactory());
  sfu.setHeaderEncoding("UFT-8");
  try {
   List<?> fileList = sfu.parseRequest(request);
   String sourceName = "";
   String extName = "";
   String name = "";
   String sfileName = "";
   for (int i = 0; i < fileList.size(); i++) {
    System.out.println("-------------------UpLoadify fileList[" + i + "]::::" + fileList.get(i));
    FileItem fi = (FileItem) fileList.get(i);
    if (!fi.isFormField()) {
     sourceName = fi.getName();
     System.out.println("-------------------UpLoadify name::::" + sourceName);
     if (sourceName == null || "".equals(sourceName.trim())) {
      continue;
     }
     if (sourceName.lastIndexOf(".") >= 0) {
      // 扩展名
      name = sourceName.substring(0,sourceName.lastIndexOf("."));
      extName = sourceName.substring(sourceName.lastIndexOf("."));
      System.out.println("-------------------UpLoadify extName::::" + extName);
     }
     // 文件名规则 前缀 + 时间 + 两位随机数 + 文件分类(标识图片尺寸) + 扩展名
     Calendar ca = Calendar.getInstance();
     DecimalFormat df = new DecimalFormat();
     df.setMinimumIntegerDigits(2);
     String st = "zxy";
     if (st != null && st.length() > 6) {
      st = st.substring(0, 6);
     }
     String dateTime = ca.get(Calendar.YEAR) + ""
       + df.format(ca.get(Calendar.MONTH)) + ""
       + df.format(ca.get(Calendar.DATE)) + ""
       + df.format(ca.get(Calendar.HOUR)) + ""
       + df.format(ca.get(Calendar.MINUTE)) + ""
       + df.format(ca.get(Calendar.SECOND));
     Random rand = new Random();
     int rand_num = rand.nextInt(89)+10;
     String fileName = st + "_" + dateTime + "_" + rand_num + extName;
     sfileName = name + "_" + dateTime + "_" + rand_num + extName;
     File saveSourceFile = new File(sourcePath + sfileName);
     File saveFile = new File(path + fileName);
     fi.write(saveSourceFile);
     fi.write(saveFile);
     System.out.println("-------------------UpLoadify fileSourceName::::" + sourceName);
     System.out.println("-------------------UpLoadify fileName::::" + fileName);
    }
   }
   response.getWriter().println(sfileName);
  } catch (FileUploadException e) {
   response.getWriter().println("0");
   e.printStackTrace();
  } catch (Exception e) {
   response.getWriter().println("0");
   e.printStackTrace();
  }
  }
}

web.xml

 <servlet>
    <servlet-name>upLoadify</servlet-name>
    <servlet-class>com.test.test.UpLoadify</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>upLoadify</servlet-name>
    <url-pattern>/uploadify</url-pattern>
  </servlet-mapping>

参数详解


设置的属性:

      id: jQuery(this).attr('id'),//绑定的input的ID

      langFile: 'http://www.static-xxx.nu/uploader/uploadifyLang_en.js',//语言包的路径,能设置所有的提示文字

      swf: 'http://www.static-xxx.nu/uploader/uploadify.swf',//[必须设置]swf的路径

      uploader: '/uploadify/galleri.php',//[必须设置]上传文件触发的url

      auto:false,//文件选择完成后,是否自动上传

      buttonText:'V?lj Filer',//上传按钮的文字

      height: 30,//上传按钮的高和宽

      width: 120,

      buttonCursor: 'pointer',//上传鼠标hover后Cursor的形状

      cancelImage: 'http://www.static-xxx.nu/uploadify-cancel.png',//[必须设置]取消图片的路径

      checkExisting:'/uploader/uploadify-check-existing.php',//检查上传文件是否存,触发的url,返回1/0

      debug: true,//debug模式开/关,打开后会显示debug时的信息

      fileObjName:'file',

      fileSizeLimit : 0,//文件的极限大小,以字节为单位,0为不限制。1MB:1*1024*1024

      fileTypeDesc: 'Bild JPG',//允许上传的文件类型的描述,在弹出的文件选择框里会显示

      fileTypeExts: '*.jpg',//允许上传的文件类型,限制弹出文件选择框里能选择的文件

      method: 'post',//和后台交互的方式:post/get

      multi: true,//是否能选择多个文件

      queueID: 'fileQueue',//显示上传文件队列的元素id,可以简单用一个div来显示

      queueSizeLimit : 999,//队列中允许的最大文件数目

      progressData : 'all', // 'percentage''speed''all'//队列中显示文件上传进度的方式:all-上传速度+百分比,percentage-百分比,speed-上传速度

      removeCompleted : true,//上传成功后的文件,是否在队列中自动删除

      removeTimeout: 3,

      requeueErrors : true,

      postData: {},//和后台交互时,附加的参数

      preventCaching : true,

      transparent: true,

      successTimeout : 30,//上传时的

      timeoutuploadLimit:999//能同时上传的文件数目

 设置的事件:

onDialogClose : function(swfuploadifyQueue) {//当文件选择对话框关闭时触发
  if( swfuploadifyQueue.filesErrored > 0 ){
  alert( '添加至队列时有'
  +swfuploadifyQueue.filesErrored
  +'个文件发生错误n'
  +'错误信息:'
  +swfuploadifyQueue.errorMsg
  +'n选定的文件数:'
  +swfuploadifyQueue.filesSelected
  +'n成功添加至队列的文件数:'
  +swfuploadifyQueue.filesQueued
  +'n队列中的总文件数量:'
  +swfuploadifyQueue.queueLength);
  }
}

onDialogOpen : function() {//当选择文件对话框打开时触发
  alert( 'Open!');
}

 

onSelect : function(file) {//当每个文件添加至队列后触发
  alert( 'id: ' + file.id
  + ' - 索引: ' + file.index
  + ' - 文件名: ' + file.name
  + ' - 文件大小: ' + file.size
  + ' - 类型: ' + file.type
  + ' - 创建日期: ' + file.creationdate
  + ' - 修改日期: ' + file.modificationdate
  + ' - 文件状态: ' + file.filestatus);
}

 

onSelectError : function(file,errorCode,errorMsg) {//当文件选定发生错误时触发
  alert( 'id: ' + file.id
  + ' - 索引: ' + file.index
  + ' - 文件名: ' + file.name
  + ' - 文件大小: ' + file.size
  + ' - 类型: ' + file.type
  + ' - 创建日期: ' + file.creationdate
  + ' - 修改日期: ' + file.modificationdate
  + ' - 文件状态: ' + file.filestatus
  + ' - 错误代码: ' + errorCode
  + ' - 错误信息: ' + errorMsg);
}

 

onQueueComplete : function(stats) {//当队列中的所有文件全部完成上传时触发
  alert( '成功上传的文件数: ' + stats.successful_uploads
  + ' - 上传出错的文件数: ' + stats.upload_errors
  + ' - 取消上传的文件数: ' + stats.upload_cancelled
  + ' - 出错的文件数' + stats.queue_errors);
}

 

onUploadComplete : function(file,swfuploadifyQueue) {//队列中的每个文件上传完成时触发一次
  alert( 'id: ' + file.id
  + ' - 索引: ' + file.index
  + ' - 文件名: ' + file.name
  + ' - 文件大小: ' + file.size
  + ' - 类型: ' + file.type
  + ' - 创建日期: ' + file.creationdate
  + ' - 修改日期: ' + file.modificationdate
  + ' - 文件状态: ' + file.filestatus
  + ' - 出错的文件数: ' + swfuploadifyQueue.filesErrored
  + ' - 错误信息: ' + swfuploadifyQueue.errorMsg
  + ' - 要添加至队列的数量: ' + swfuploadifyQueue.filesSelected
  + ' - 添加至对立的数量: ' + swfuploadifyQueue.filesQueued
  + ' - 队列长度: ' + swfuploadifyQueue.queueLength);
}

 onUploadError : function(file,errorCode,errorMsg,errorString,swfuploadifyQueue) {

//上传文件出错是触发(每个出错文件触发一次)
  alert( 'id: ' + file.id
  + ' - 索引: ' + file.index
  + ' - 文件名: ' + file.name
  + ' - 文件大小: ' + file.size
  + ' - 类型: ' + file.type
  + ' - 创建日期: ' + file.creationdate
  + ' - 修改日期: ' + file.modificationdate
  + ' - 文件状态: ' + file.filestatus
  + ' - 错误代码: ' + errorCode
  + ' - 错误描述: ' + errorMsg
  + ' - 简要错误描述: ' + errorString
  + ' - 出错的文件数: ' + swfuploadifyQueue.filesErrored
  + ' - 错误信息: ' + swfuploadifyQueue.errorMsg
  + ' - 要添加至队列的数量: ' + swfuploadifyQueue.filesSelected
  + ' - 添加至对立的数量: ' + swfuploadifyQueue.filesQueued
  + ' - 队列长度: ' + swfuploadifyQueue.queueLength);
}

 

onUploadProgress : function(file,fileBytesLoaded,fileTotalBytes,queueBytesLoaded,swfuploadifyQueueUploadSize) {

//上传进度发生变更时触发
      alert( 'id: ' + file.id
  + ' - 索引: ' + file.index
  + ' - 文件名: ' + file.name
  + ' - 文件大小: ' + file.size
  + ' - 类型: ' + file.type
  + ' - 创建日期: ' + file.creationdate
  + ' - 修改日期: ' + file.modificationdate
  + ' - 文件状态: ' + file.filestatus
  + ' - 当前文件已上传: ' + fileBytesLoaded
  + ' - 当前文件大小: ' + fileTotalBytes
  + ' - 队列已上传: ' + queueBytesLoaded
  + ' - 队列大小: ' + swfuploadifyQueueUploadSize);
}

onUploadStart: function(file) {//上传开始时触发(每个文件触发一次)
  alert( 'id: ' + file.id
  + ' - 索引: ' + file.index
  + ' - 文件名: ' + file.name
  + ' - 文件大小: ' + file.size
  + ' - 类型: ' + file.type
  + ' - 创建日期: ' + file.creationdate
  + ' - 修改日期: ' + file.modificationdate
  + ' - 文件状态: ' + file.filestatus );
}

onUploadSuccess : function(file,data,response) {//上传完成时触发(每个文件触发一次)
  alert( 'id: ' + file.id
  + ' - 索引: ' + file.index
  + ' - 文件名: ' + file.name
  + ' - 文件大小: ' + file.size
  + ' - 类型: ' + file.type
  + ' - 创建日期: ' + file.creationdate
  + ' - 修改日期: ' + file.modificationdate
  + ' - 文件状态: ' + file.filestatus
  + ' - 服务器端消息: ' + data
  + ' - 是否上传成功: ' + response);


uploadify-v3.1 源代码下载

原创粉丝点击