- /**
- * Struts2Test
- * 顺便的文件下载的Action
- */
- package com.labci.struts2.action;
- import java.io.FileInputStream;
- import java.io.InputStream;
- import java.io.OutputStream;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.struts2.interceptor.ServletRequestAware;
- import org.apache.struts2.interceptor.ServletResponseAware;
- import com.opensymphony.xwork2.ActionSupport;
- /**
- * @author Bill Tu(tujiyue/iwtxokhtd)
- * Jun 8, 2011[9:15:15 PM]
- *
- */
- public class DownloadFileAction extends ActionSupport implements
- ServletRequestAware, ServletResponseAware {
- /**
- *
- */
- private static final long serialVersionUID = -7448748577778248376L;
- private HttpServletRequest request;
- private HttpServletResponse response;
- private String savePath;
- @Override
- public String execute() throws Exception {
- String fileName=request.getParameter("fileName");
- String fullPath=getSavePath()+"//"+fileName;
- fileName=new String(fileName.getBytes("utf-8"),"iso-8859-1");
- InputStream is=new FileInputStream(fullPath);
- int len=0;
- byte []buffers=new byte[1024];
- response.reset();
- response.setContentType("application/x-msdownload");
- response.addHeader("Content-Disposition", "attachment;filename=/""+fileName+"/"");
- //把文件内容通过输出流打印到页面上供下载
- while((len=is.read(buffers))!=-1){
- OutputStream os=response.getOutputStream();
- os.write(buffers, 0, len);
- }
- is.close();
- return SUCCESS;
- }
- public void setServletRequest(HttpServletRequest req) {
- this.request=req;
- }
- public void setServletResponse(HttpServletResponse resp) {
- this.response=resp;
- }
- @SuppressWarnings("deprecation")
- public String getSavePath() {
- return request.getRealPath(savePath);
- }
- public void setSavePath(String savePath) {
- this.savePath = savePath;
- }
- }
- /**
- * Struts2Test
- * 使用Struts2上传文件
- */
- package com.labci.struts2.action;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.util.List;
- import javax.servlet.http.HttpServletRequest;
- import org.apache.struts2.interceptor.ServletRequestAware;
- import com.opensymphony.xwork2.ActionSupport;
- /**
- * @author Bill Tu(tujiyue/iwtxokhtd)
- * Jun 8, 2011[8:31:01 PM]
- *
- */
- public class UploadFileAction extends ActionSupport implements
- ServletRequestAware {
- /**
- *
- */
- private static final long serialVersionUID = -1896915260152387341L;
- private HttpServletRequest request;
- public void setServletRequest(HttpServletRequest req) {
- this.request=req;
- }
- private List<File> fileName;//这里的"fileName"一定要与表单中的文件域名相同
- private List<String> fileNameContentType;//格式同上"fileName"+ContentType
- private List<String> fileNameFileName;//格式同上"fileName"+FileName
- private String savePath;//文件上传后保存的路径
- public List<File> getFileName() {
- return fileName;
- }
- public void setFileName(List<File> fileName) {
- this.fileName = fileName;
- }
- public List<String> getFileNameContentType() {
- return fileNameContentType;
- }
- public void setFileNameContentType(List<String> fileNameContentType) {
- this.fileNameContentType = fileNameContentType;
- }
- public List<String> getFileNameFileName() {
- return fileNameFileName;
- }
- public void setFileNameFileName(List<String> fileNameFileName) {
- this.fileNameFileName = fileNameFileName;
- }
- @SuppressWarnings("deprecation")
- public String getSavePath() {
- return request.getRealPath(savePath);
- }
- public void setSavePath(String savePath) {
- this.savePath = savePath;
- }
- @Override
- public String execute() throws Exception {
- File dir=new File(getSavePath());
- if(!dir.exists()){
- dir.mkdirs();
- }
- List<File> files=getFileName();
- for(int i=0;i<files.size();i++){
- FileOutputStream fos=new FileOutputStream(getSavePath()+"//"+getFileNameFileName().get(i));
- FileInputStream fis=new FileInputStream(getFileName().get(i));
- byte []buffers=new byte[1024];
- int len=0;
- while((len=fis.read(buffers))!=-1){
- fos.write(buffers,0,len);
- }
- }
- return SUCCESS;
- }
- }
- <?xml version="1.0" encoding="UTF-8" ?>
- <!DOCTYPE struts PUBLIC
- "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
- "http://struts.apache.org/dtds/struts-2.0.dtd">
- <struts>
- <constant name="struts.devMode" value="false" />
- <!-- 改变struts2默认为2M的上传文件大小限制 -->
- <constant name="struts.multipart.maxSize" value="1024000000"/>
- <package name="upload" extends="struts-default">
- <action name="uploadFile" class="com.labci.struts2.action.UploadFileAction">
- <param name="savePath">/upload</param>
- <result name="success">index.jsp</result>
- </action>
- <action name="downloadFile" class="com.labci.struts2.action.DownloadFileAction">
- <param name="savePath">/upload</param>
- <result name="success">index.jsp</result>
- </action>
- </package>
- </struts>
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
- http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
- <filter>
- <filter-name>struts2</filter-name>
- <filter-class>
- org.apache.struts2.dispatcher.FilterDispatcher
- </filter-class>
- </filter>
- <filter-mapping>
- <filter-name>struts2</filter-name>
- <url-pattern>*.action</url-pattern>
- </filter-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
- <%@ page language="java" contentType="text/html;charset=utf-8" pageEncoding="utf-8"%>
- <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>Struts2结合JQuery.uploadify实现带进度的多文件上传示例</title>
- <link href="js/uploadify.css" mce_href="js/uploadify.css" rel="stylesheet" type="text/css"/>
- <mce:script type="text/javascript" src="js/jquery-1.4.2.min.js" mce_src="js/jquery-1.4.2.min.js" ></mce:script>
- <mce:script type="text/javascript" src="js/swfobject.js" mce_src="js/swfobject.js" ></mce:script>
- <mce:script type="text/javascript" src="js/jquery.uploadify.v2.1.4.min.js" mce_src="js/jquery.uploadify.v2.1.4.min.js" ></mce:script>
- <mce:script type="text/javascript"><!--
- $(function() {
- $("#cancelBtn").hide();
- $("#full").hide();
- $('#strutsUploadFile').uploadify({
- 'uploader' : 'js/uploadify.swf',
- 'script' : 'uploadFile.action',
- 'cancelImg' : 'js/cancel.png',
- 'fileDataName':'fileName',
- //解决中文按钮名的好方式
- 'buttonImg' : 'images/select.jpg',
- //可选
- 'height' : 20,
- //可选
- 'width' : 50,
- //设置允许上传的文件格式
- //'fileExt' : '*.jpg;*.gif;*.png',
- //设置允许上传的文件格式后,必须加上下面这行代码才能帮你过滤
- //'fileDesc' : 'Image Files',
- //允许连续上传多个文件
- 'multi':'true',
- //一次性最多允许上传多少个,不设置的话默认为999个
- 'queueSizeLimit' : 3,
- //每个文件允许上传的大小(字节)
- //'sizeLimit' : 102400,
- 'onComplete' : function(event, ID, fileObj, response, data) {
- //当每个文件上传完成后的操作
- $("#cancel").hide();
- $("#full").hide();
- $("#show").append( "<a href="/" mce_href="/""downloadFile.action?fileName="+fileObj.name+"/">"+fileObj.name+"</a><br/>");
- },
- 'onAllComplete':function(event,data) {
- //当所有文件上传完成后的操作
- $("#cancelBtn").hide();
- if(data.errors==0){
- $("#allShow").append("所有文件已上传成功(本次共上传"+data.filesUploaded+"个),上传总大小:"+data.allBytesLoaded+"字节,平均传输速度:"+data.speed+"KB/s");
- }else{
- $("#allShow").append("成功上传"+data.filesUploaded+"个文件,失败"+data.errors+"个,上传总大小:"+data.allBytesLoaded+"字节,平均传输速度:"+data.speed+"KB/s");
- }
- },
- 'onOpen': function(event,ID,fileObj) {
- //当有文件正在上传时的操作
- $("#cancelBtn").show();
- },
- 'onQueueFull': function (event,queueSizeLimit) {
- //当添加待上传的文件数量达到设置的上限时的操作
- $("#full").append("<font color='red'><b>已经达到上传数量限制了,不能再添加了</b></color><br/>");
- $("#full").show();
- return false;
- },
- 'onCancel': function(event,ID,fileObj,data) {
- //当取消所有正在上传文件后的操作
- $("#cancelBtn").hide();
- }
- });
- });
- // --></mce:script>
- </head>
- <body>
- <div id="full"></div>
- <div id="allShow"></div>
- <div id="show"></div>
- <input type="file" name="fileName" id="strutsUploadFile"/><br/>
- <input type="button" οnclick="javascript:$('#strutsUploadFile').uploadifyUpload()" value="确定上传"/>
- <input type="button" id="cancelBtn" οnclick="javascript:$('#strutsUploadFile').uploadifyClearQueue()" value="取消上传"/>
- </body>
- </html>
只要有文件正在上传,则会出现“取消上传”按钮供取消所有上传文件
上传成功后可点相应链接进行下载:
添加待上传文件数量超过设置上传数量时的情况:
其它的操作细节不再列举。