uploadify 文件上传 struts2

来源:互联网 发布:linux ansi 控制码 编辑:程序博客网 时间:2024/05/01 22:58

多文件上传文件,jquery.uploadify常用参数介绍,和基本代码片段。

参数说明:(红色的属性代表常用的)

1

uploader

上传控件的主体文件,flash控件

   默认值='uploadify.swf'

2

script

 

相对路径的后端脚本,它将处理您上传的文件。

绝对路径前缀或'/'或'http'的路径

  默认值='uploadify.php'

3

checkScript

 

检查该文件是否已经选择驻留在服务器上。
没有默认值。 官方例子中'check.php'是提供核心文件

4

scriptData

 

可提供URL传递参数。用来传递get参数。例如:

  index.jsp?id=1&action=uploadify可以设置成:

'script': 'index.jsp',

'scriptData':{'id':1,'action':'uploadify'},

注:要设置‘method’:‘GET’.

 

5

fileDataName

 

 您的文件在上传服务器脚本阵列的名称。
   默认值='Filedata'

6

method

 

 设置为发送到后端脚本的方法。要么'get'或post'。

   默认值'post'

7

scriptAccess

 

 flash脚本文件的访问模式,如果在本地测试设置为always,默认值:sameDomain

8

folder

 

您想将文件保存到的路径。考虑到安全问题,一般并不在客户端设定后供服务器得到所存的路径。我试了下。这个参数好像以get的方式传递的。设定post得不到这个值。

9

queueID

 

 文件队列ID。与div的id一致。参考上一篇例子的用法。

10

queueSizeLimit

 

限制在一次队列中的次数(可选定几个文件)。默认值= 999,而一次可传几个文件有 simUploadLimit属性决定

11

multi

 

是否支持上传多文件,可设定true或false。

  默认false。设定true时,选中的文件是当前项。

12

auto

 

选定文件后是否自动上传,可设定true或false。

  默认false

13

fileDesc

 

出现在上传对话框中的文件类型描述。与fileExt需同时使用

14

fileExt

 

支持的格式,启用本项时需同时声明fileDesc。

如:‘*.rar,*.doc

 

15

sizeLimit

 

控制上传文件的大小,单位byte

16

simUploadLimit

 

多文件上传时,同时上传文件数目限制。默认1

  一次可传几个文件。

17

buttonText

 

默认按钮的名字。默认BROWER

18

buttonImg

使用图片按钮,设定图片的路径即可。

19

hideButton

 

上传按钮的隐藏。true 或false。默认flase

20

rollover

 

值为true和false,设置为true时当鼠标移到浏览按钮上时有反转效果。

21

width

 

 按钮图片的长度。默认 110

22

height

 

 按钮图片的高度。默认 30

23

wmode

 

 背景透明transparent 与不透明opaque设定。默认 不透明

 

24

cancelImg

 

 取消按钮。设定图片路径。默认cancel.png

 

 

25

onInit

 

函数, 初始化时的状态。

onInit: function() { 

$("#id").html("上传前");},

26

onComplete

 

文件上传后触发

函数:可传递五个参数event,queueID,fileObj.response,data

event: 事件对象

queueID: 完成文件的唯一标识符。

fileObj:  

   name – 文件名

   filepath –上传路径

   size – 文件大小

   creationDate – 文件创建时间

   modificationDate –文件最近修改时间

   type –文件的扩展名

response: 服务器回调的数据

data:  

   fileCount – The total number of files left in the queue

   speed – 平均上传速度 KB/s

如:

onComplete: function(event, queueID, fileObj) {

  alert("文件:" +fileObj.name + "上传失败");  }

 

27

onSelectOnce

 

在单文件或多文件上传时,选择文件时触发。

函数:可传递二个参数,event,data

event: The event object.

data: An object containing details about the select operation.

   fileCount – The total number of files in the queue

   filesSelected – The number of files selected in the select operation

   filesReplaced – The number of files that were replaced in the queue

   allBytesTotal – The total number of bytes for all files in the queue

 

28

onCancel

 

当点击文件队列中文件的关闭按钮或点击取消上传时触发,file参数为被取消上传的文件对象

函数:可传递四个参数,event,queueID,fileObj,data

event: The event object.

queueID: The unique identifier of the file that was cancelled.

fileObj: An object containing details about the file that was selected.

    name – The name of the file

    size – The size in bytes of the file

    creationDate – The date the file was created

    modificationDate – The last date the file was modified

    type – The file extension beginning with a '.'

 

data: Details about the file queue.

    fileCount – The total number of files left in the queue

    allBytesTotal – The total number of bytes left for all files in the queue

 

29

onClearQueue

 

当调用函数fileUploadClearQueue时触发。

函数:可传递二个参数event和data

event: The event object.

30

onQueueFull

 

当设置了queueSizeLimit并且选择的文件个数超出了queueSizeLimit的值时触发。

函数:可传递二个参数event,queueSizeLimit

 event - The event object.

 queueSizeLimit - The maximum size of the queue.

 

31

onError

 

当上传过程中发生错误时触发。

 函数有四个参数:event、queueId、fileObj、errorObj

event: The event object.

queueID: The unique identifier of the file that was errored.

fileObj: An object containing details about the file that was selected.

   name – The name of the file

   size – The size in bytes of the file

   creationDate – The date the file was created

   modificationDate – The last date the file was modified

  • type – The file extension beginning with a '.'

errorObj: An object containing details about the error returned.

  • type – Either 'HTTP', 'IO', or 'Security'

  • info – An error message describing the type of error returned

 

32

onOpen

 

点击上传时触发

函数:可传递三个参数 event,queueID,fileObj

event: The event object.

queueID: The unique identifier of the file that was opened.

fileObj: An object containing details about the file that was selected.

   name – The name of the file

   size – The size in bytes of the file

  • creationDate – The date the file was created

   modificationDate – The last date the file was modified

   type – The file extension beginning with a '.'

 

33

onProgress

 

 

击上传时触发,如果auto设置为true则是选择文件时触发,如果有多个文件上传则遍历整个文件队列,在onOpen之后触发。

函数:可传递四个参数 event,queueID,fileObj,data

event: The event object.

queueID: The unique identifier of the file that was updated.

fileObj: An object containing details about the file that was selected.

   name – The name of the file

   size – The size in bytes of the file

   creationDate – The date the file was created

   modificationDate – The last date the file was modified

   type – The file extension beginning with a '.'

 

data: An object containing details about the upload and queue.

   percentage – The current percentage completed for the upload

   bytesLoaded – The current amount of bytes uploaded

   allBytesLoaded – The current amount of bytes loaded for all files in the queue

   speed – The current upload speed in KB/s

 

34

onSelect

 

 

event: The event object.

queueID: The unique identifier of the file that was selected.

fileObj: An object containing details about the file that was selected.

   name – The name of the file

   size – The size in bytes of the file

   creationDate – The date the file was created

   modificationDate – The last date the file was modified

   type – The file extension beginning with a '.'

 

35

onAllComplete

 

 

文件队列中所有的文件上传完成后触发。

函数:可传递二个参数 event,data

event: The event object.

data: An object containing details about the upload process.

   filesUploaded – The total number of files uploaded

   errors – The total number of errors while uploading

   allbytesLoaded – The total number of bytes uploaded

   speed – The average speed of all uploaded files

 

36

onCheck

 

 当检查到服务器已存在此文件时触发此事件,默认事件是弹出确认框.

函数:可传递五个参数event,checkScript,fileQueue,folder,singer

 

event: The event object.

checkScript: The path to the file checking script.

fileQueue: A file queue object consisting of  key/value pairs with the queue ID as the key and the filename as the value.

folder: The path to the upload folder.

single: True if only one file is being uploaded from the queue.


 

下面为实现上传功能的代码片段

//jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
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%>">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>My JSP 'index.jsp' starting page</title>
 <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">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
 <script src="js/jquery-1.7.min.js"></script>
 <script language="javascript"  src="js/swfobject.js"></script>
 <script language="javascript"  src="js/jquery.uploadify.v2.1.0.min.js"></script>
 <style type="text/css">
  body {
   font: 12px/16px Arial, Helvetica, sans-serif;
  }
  #fileQueue {
   width: 400px;
   height: 300px;
   overflow: auto;
   border: 1px solid #E5E5E5;
   margin-bottom: 10px;
  }
 </style>
  </head>
 
   <body>  
 <a href="javascript:(0)"><input type="file" name="fileInput" id="fileInput" /></a>  &nbsp;&nbsp;&nbsp;&nbsp;
 <a href="javascript:$('#fileInput').uploadifyUpload();"  >开始上传</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  
 <a href="javascript:$('#fileInput').uploadifyClearQueue();"  >取消上传队列</a> <br>  <br>
    <div id="result"></div><!--显示结果-->  
       <div id="fileQueue"></div> 
  </body> 
</html>
<script type="text/javascript">
     function showResult(){//删除显示的上传成功结果  
          $("#result").html("");  
        }  
    $(document).ready(function() {
        var num=0;
        $('#fileInput').uploadify({  
   'uploader': 'js/swf/uploadify.swf',//uploadify.swf 文件的相对路径
        'script': 'dataImport_fileImport.action',   //指定服务端处理类的入口
        'folder': 'fileImport',  
   'cancelImg': 'images/cancel.png',//单个文件取消的按钮图片
        'fileDataName': 'fileInput', //和input的name属性值保持一致就好,Struts2就能处理了  
        'queueID': 'fileQueue',
        'queueSizeLimit':5,//每次最大上传文件数 
        'fileDesc':'请选择xls文件',//限制上传文件
        'fileExt': '*.xls', //fileDesc与fileExt联合使用
        'auto': false,//是否选取文件后自动上传  
        'multi': true,//是否支持多文件上传
        'simUploadLimit' : 5,// 允许同时上传的个数
        'buttonText': 'Browse Files',//按钮上的文字 
        'displayData': 'percentage',//有speed和percentage两种,一个显示速度,一个显示完成百分比   
  'onCancel':function(event,queueID,fileObj,data){$("#result").html("");},//当点击文件队列中文件的关闭按钮或点击取消上传时触发,file参数为被取消上传的文件对象
  'onSelectOnce':function(event,data){$("#result").html("");},//在单文件或多文件上传时,选择文件时触发。
  'onOpen':function(event,queueID,fileObj){$("#result").html("");},//点击上传时触发
        'onComplete': function (event, queueID, fileObj, response, data){  //点击上传时触发
            if(response>0){
                num=num+parseInt(response);
             }
            if(data.fileCount==0){
             $("#result").html("上传成功"+num+"条数据;\n");//显示上传成功结果
                num=0;
                }
          },
          'onAllComplete':function(event,data) {  //文件队列中所有的文件上传完成后触发。
              //当所有文件上传完成后的操作 
              $("#cancelBtn").hide(); 
              if(data.errors==0){ 
                  $("#result").append("所有文件已上传成功(本次共上传"+data.filesUploaded+"个),上传总大小:"+data.allBytesLoaded+"字节,平均传输速度:"+data.speed+"KB/s"); 
              }else{ 
                  $("#result").append("成功上传"+data.filesUploaded+"个文件,失败"+data.errors+"个,上传总大小:"+data.allBytesLoaded+"字节,平均传输速度:"+data.speed+"KB/s"); 
              } 
        },
        'onError': function(event, queueID, fileObj) {
            alert("文件:" + fileObj.name + " 上传失败");
        }
        }); 
    }); 
</script> 

//struts2   action页面


package dataimport;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;

public class DataImportAction {
 private File fileInput;  
 private String fileInputFileName;
 
 public File getFileInput() {
  return fileInput;
 }
 public void setFileInput(File fileInput) {
  this.fileInput = fileInput;
 }
 public String getFileInputFileName() {
  return fileInputFileName;
 }
 public void setFileInputFileName(String fileInputFileName) {
  this.fileInputFileName = fileInputFileName;
 }
 private int sum=0;
 
 /**
  * 资源数据导入功能
  */
 public void  fileImport(){
  System.out.println("进入方法              fileImport");
  HttpServletResponse reponse=(HttpServletResponse) ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE);
  PrintWriter pw;
  int index=fileInputFileName.lastIndexOf(".");
  String path=fileInputFileName.substring(index, fileInputFileName.length());
  try {
  if(".xls".equals(path)){
   sum++;
  }
   pw=reponse.getWriter();
   pw.print(sum);
   pw.flush();
   pw.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

//struts.xml

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
 <constant name="struts.i18n.encoding" value="utf-8"></constant>
 <!-- 设置最大上传的大小 -->
 <constant name="struts.multipart.maxSize" value="4000194304"/>
 <constant name="struts.enable.DynamicMethodInvocation" value="true"/>
 <constant name="struts.multipart.saveDir" value="/temp"></constant><!-- file文件存放位置 -->
 <package name="uploadfile" namespace="/" extends="struts-default">
  <action name="dataImport_*" class="dataimport.DataImportAction" method="{1}">
  </action>
 </package>
 </struts>   

 

 

注:如果页面不出现如图所示的Browse Files,检查浏览器是否安装播放flash插件,或者还原浏览器的出厂值,如有问题请告之谢谢!

 

原创粉丝点击