struts2.0多附件上传

一、上传单个文件

上传文件是很多Web程序都具有的功能。在Struts1.x中已经提供了用于上传文件的组件。而在Struts2中提供了一个更为容易操作的上传文件组 件。所不同的是,Struts1.x的上传组件需要一个ActionForm来传递文件,而Struts2的上传组件是一个拦截器(这个拦截器不用配置, 是自动装载的)。在本文中先介绍一下如何用struts2上传单个文件,最后介绍一下用struts2上传任意多个文件。

要用Struts2实现上传单个文件的功能非常容易实现,只要使用普通的Action即可。但为了获得一些上传文件的信息,如上传文件名、上传文件类型以 及上传文件的Stream对象,就需要按着一定规则来为Action类增加一些getter和setter方法。

在Struts2中,用于获得和设置java.io.File对象(Struts2将文件上传到临时路径,并使用java.io.File打开这个临时文 件)的方法是getUpload和setUpload。获得和设置文件名的方法是getUploadFileName和 setUploadFileName,获得和设置上传文件内容类型的方法是getUploadContentType和 setUploadContentType。下面是用于上传的动作类的完整代码:


package action; 

import java.io.*;
import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport
{
private File upload;
private String fileName;
private String uploadContentType;

public String getUploadFileName()
{
return fileName;
}

public void setUploadFileName(String fileName)
{
this.fileName = fileName;
}

public File getUpload()
{
return upload;
}

public void setUpload(File upload)
{
this.upload = upload;
}
public void setUploadContentType(String contentType)
{
this.uploadContentType=contentType;

}

public String getUploadContentType()
{
return this.uploadContentType;
}
public String execute() throws Exception
{
java.io.InputStream is = new java.io.FileInputStream(upload);
java.io.OutputStream os = new java.io.FileOutputStream("d:\\upload\\" + fileName);
byte buffer[] = new byte[8192];
int count = 0;
while((count = is.read(buffer)) > 0){
os.write(buffer, 0, count);
}
os.close();
is.close();
return SUCCESS;
}
}



在execute方法中的实现代码就很简单了,只是从临时文件复制到指定的路径(在这里是d:\upload)中。上传文件的临时目录的默认值是 javax.servlet.context.tempdir的值,但可以通过struts.properties(和struts.xml在同一个目录 下)的struts.multipart.saveDir属性设置。Struts2上传文件的默认大小限制是2M(2097152字节),也可以通过 struts.properties文件中的struts.multipart.maxSize修改,如 struts.multipart.maxSize=2048 表示一次上传文件的总大小不能超过2K字节。

下面的代码是上传文件的JSP页面代码:


<%@ page language="java" import="java.util.*" pageEncoding="GBK"%> 
<%@ taglib prefix="s" uri="/struts-tags"%>

<html>
<head>
<title>上传单个文件</title>
</head>

<body>
<s:form action="upload" namespace="/test"
enctype="multipart/form-data">
<s:file name="upload" label="输入要上传的文件名" />
<s:submit value="上传" />
</s:form>

</body>
</html>



也可以在success.jsp页中通过<s:property>获得文件的属性(文件名和文件内容类型),代码如下:

<s:property value="uploadFileName"/> 


二、上传任意多个文件

在Struts2中,上传任意多个文件也非常容易实现。首先,要想上传任意多个文件,需要在客户端使用DOM技术生成任意多个<input type=”file” />标签。name属性值都相同。代码如下:

<html> 
<head>
<script language="javascript">
var id = 0;
function addComponent()
{
id = id+1;
if(id >= 5){
alert("最多五个附件!");
return;
}
var uploadHTML = document.createElement( "<input type='file' id='file' name='uploadFile' style='width:50%;'/>");
document.getElementById("files").appendChild(uploadHTML);
uploadHTML = document.createElement( "<p/>");
document.getElementById("files").appendChild(uploadHTML);
}
function clearFile()
{
var file = document.getElementsByName("uploadFile");
for(var i=0;i<file.length;i++)
{
file[i].outerHTML=file[i].outerHTML.replace(/(value=\").+\"/i,"$1\"");
}
}
</script>
</head>
<body>
<input type="button" onclick="addComponent();" value="添加文件" />
<br />
<form onsubmit="return true;" action="/struts2/test/upload.action"
method="post" enctype="multipart/form-data">
<table width="100%">
<tr>
<td style="text-align:center">
<font style="color: red; font-size: 14px;">上传附件(文件大小请控制在20M以内)</font>
</td>
</tr>
<tr>
<td><a href="###" class="easyui-linkbutton" onclick="addComponent();" iconCls="icon-add">添加文件(最多五个附件)</a> <br /> <span id="files">
<input type='file' name='uploadFile' style='width:50%;'/><p/>
</span>
<input type='button' value='重置' stytle='btng' onclick='clearFile();'/>
</td>
</tr>
</table>
</form>
</body>

</html>

上面的javascript代码可以生成任意多个<input type=’file’>标签,name的值都为file(要注意的是,上面的javascript代码只适合于IE浏览器,firefox等其他 浏览器需要使用他的代码)。至于Action类,和上传单个文件的Action类基本一至,只需要将三个属性的类型改为List即可。代码如下:
package action;

import java.io.*; 
import com.opensymphony.xwork2.ActionSupport;

public class UploadMoreAction extends ActionSupport
{
private List<File> uploadFile;
private List<String> uploadFileFileName;
private List<String> uploadFileContentType;

public List<File> getUploadFile() {
return uploadFile;
}

public void setUploadFile(List<File> uploadFile) {
this.uploadFile = uploadFile;
}

public List<String> getUploadFileFileName() {
return uploadFileFileName;
}

public void setUploadFileFileName(List<String> uploadFileFileName) {
this.uploadFileFileName = uploadFileFileName;
}

public List<String> getUploadFileContentType() {
return uploadFileContentType;
}

public void setUploadFileContentType(List<String> uploadFileContentType) {
this.uploadFileContentType = uploadFileContentType;
}
public String execute() throws Exception
{
if(uploadFile != null){
Map<String, Object> paraMap = new HashMap<String, Object>();
paraMap.put("deptCode", this.getLoginUserDepartment().getDeptCode());
paraMap.put("workId", lawVersion.getId());
ProjectComm pc = new ProjectComm();
pc.saveFile(paraMap,CommCode.apkPath, this.getLoginUser(), uploadFile, uploadFileFileName, ".jpg");
}
return SUCCESS;
}
}


common.properties

UPLOAD_PATH=/virtualdir/upload/
#photo upload
PHOTO_PATH=/data/photo/



public static String getPorjectPath(String classesPath){
String tempdir;
String classPath[] = classesPath.split("webapps");
tempdir=classPath[0];
if(!"/".equals(tempdir.substring(tempdir.length()))){
tempdir += File.separator;
}
return tempdir;
}



File.separator//可以不用


FileUtil.java

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.jshx.ictjs.httptransfer.utils.DateTools;
import com.jsict.core.PropertiesManager;
import com.jsict.core.exception.IctException;
import com.jsict.ictmap.web.UserSession;
import com.jsict.util.IctUtil;
import com.jsict.util.StringUtil;




private static final Logger logger = Logger.getLogger(FileUtil.class);

/**
* 保存多文件
* @param paraMap 参数
* @param userSession 登录用户
* @param uploadFile 文件列表
* @param uploadFileFileName 文件表列表
* @param fileType 文件类型
* @throws IOException
* @throws IctException
*/
public void saveFileList(Map<String,Object> paraMap,UserSession userSession,List<File> uploadFile,List<String> uploadFileFileName,String fileType) throws IOException, IctException{
String dateNowStr=DateTools.parseDate2Str(new Date(), "yyyyMM");
String savePath = PropertiesManager.getProperty("common.properties", "PHOTO_PATH") + dateNowStr;
String loginName = CommonFunc.getMapByValue(paraMap, "loginName");
if(!StringUtil.isEmpty(loginName)){
savePath = savePath + "/" + loginName;
}
String classesPath = this.getClass().getClassLoader().getResource("").getPath();
logger.debug("=============Constant.getPorjectPath()=" + classesPath);
String photoPath = Constant.getPorjectPath(classesPath) +
PropertiesManager.getProperty("common.properties", "UPLOAD_PATH")+savePath;
FileUtil fileUtil = new FileUtil();
ServiceFunc sf = new ServiceFunc();
if (uploadFile != null){
for (int i = 0; i < uploadFile.size(); i++){
String endSavePath = fileUtil.saveFile(photoPath, savePath,uploadFile.get(i),uploadFileFileName.get(i),fileType);
if(!StringUtil.isEmpty(endSavePath)){
sf.savePhoto(paraMap, userSession, endSavePath);
}
}
}
}

/**
* 保存文件
* @param photoPath 文件真实保存路径
* @param savePath DB中保存的路径
* @param file 文件流
* @param filename 文件名称
* @param fileType 文件类型
* @return
* @throws IOException
*/
public String saveFile(String photoPath,String savePath,File file,String fileName,String fileType) throws IOException{
createFolder(photoPath);
java.io.InputStream is = null;
java.io.OutputStream os = null;
try {
String newName = getDatedFName(fileName,fileType);
String endPath = photoPath + "/"+ newName;
String endSavePath = savePath + "/"+ newName;

endPath = endPath.replace(" ", "");
endSavePath = endSavePath.replace(" ", "");

createFile(endPath.toString().trim());
os = new java.io.FileOutputStream(endPath);
is = new java.io.FileInputStream(file);
byte buffer[] = new byte[8192];
int count = 0;
while ((count = is.read(buffer)) > 0){
os.write(buffer, 0, count);
}
return endSavePath;
} catch (IOException e) {
}finally {
if (null != is)
is.close();
if (null != os)
os.close();
}
return null;
}


/**
* 保存文件
* @param request 获得二进制流
* @param savePath 保存相对路径
* @param filename 文件名称
* @param fileType 文件类型
* @return
* @throws IOException
*/
public String saveFile(HttpServletRequest request,String savePath,String fileName,String fileType) throws IOException{

String classesPath = this.getClass().getClassLoader().getResource("").getPath();
logger.debug("=============Constant.getPorjectPath()=" + classesPath);
String photoPath = Constant.getPorjectPath(classesPath) +
PropertiesManager.getProperty("common.properties", "UPLOAD_PATH")+savePath;
createFolder(photoPath);
FileOutputStream fos = null;
BufferedInputStream bis = null;
try {
String newName = getDatedFName(fileName,fileType);
String endPath = photoPath + "/"+ newName;
String endSavePath = savePath + "/"+ newName;

endPath = endPath.replace(" ", "");
endSavePath = endSavePath.replace(" ", "");

createFile(endPath.toString().trim());
fos = new java.io.FileOutputStream(endPath);
bis = new BufferedInputStream(request.getInputStream());
byte buffer[] = new byte[8192];
int count = 0;
while ((count = bis.read(buffer)) > 0){
fos.write(buffer, 0, count);
}
return endSavePath;
} catch (IOException e) {
}finally {
if (null != bis)
bis.close();
if (null != fos)
fos.close();
}
return null;
}

/**
* 新建文件夹
* @param photoPath
*/
private void createFolder(String photoPath){
File outdir = new File(photoPath.toString().trim());
if (!outdir.exists()){
outdir.mkdirs();
}
}

/**
* 新建文本
* @param endPath 文件真实保存路径
* @throws IOException
*/
private void createFile(String endPath) throws IOException{
File outfile = new File(endPath.toString().trim());
if (logger.isDebugEnabled()){
logger.debug("outfile:" + outfile.getPath());
}
if (!outfile.exists()){
outfile.createNewFile();
}
}

/**
* <照片名前加上日期>
* @param filename 文件名称
* @param fileType 文件类型
* @return
*/
public String getDatedFName(String filename,String fileType) {

String fnameSplit[] = filename.split("\\.");

StringBuffer result = new StringBuffer();
int ronNum = (int)(Math.random()*1000);
String dateSfx = IctUtil.getCurrTime() + "_" +ronNum;
if(!StringUtil.isEmpty(fnameSplit[0])){
result.append(fnameSplit[0]+"_");
}
result.append(dateSfx);
result.append(fileType);
return result.toString();
}

/**
* 删除某个文件夹下的所有文件夹和文件
*
* @param delpath
* String
* @throws FileNotFoundException
* @throws IOException
* @return boolean
*/
public static boolean deletefile(String delpath) throws Exception {
try {

File file = new File(delpath);
// 当且仅当此抽象路径名表示的文件存在且 是一个目录时,返回 true
if (!file.isDirectory()) {
file.delete();
} else if (file.isDirectory()) {
String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
File delfile = new File(delpath + "\\" + filelist[i]);
if (!delfile.isDirectory()) {
delfile.delete();
System.out
.println(delfile.getAbsolutePath() + "删除文件成功");
} else if (delfile.isDirectory()) {
deletefile(delpath + "\\" + filelist[i]);
}
}
System.out.println(file.getAbsolutePath()+"删除成功");
file.delete();
}

} catch (FileNotFoundException e) {
System.out.println("deletefile() Exception:" + e.getMessage());
}
return true;
}



在execute方法中,只是对List对象进行枚举,在循环中的代码和上传单个文件时的代码基本相同。如果读者使用过struts1.x的上传组件,是 不是感觉Struts2的上传功能更容易实现呢?在Struts1.x中上传多个文件时,可是需要建立带索引的属性的。而在Struts2中,就是这么简 单就搞定了。图1是上传任意多个文件的界面。


在struts.xml中可以控制上传的大小

<constant name="struts.multipart.maxSize" value="20485760" />
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值