复习一下基于Struts2的文件上传下载
这部分是上传功能,支持多个文件的上传,允许限定上传的文件类型
实例中,以限定上传文件为图片格式为例
转载请注明出处:http://blog.csdn.net/u012219290
基本效果:
选择文件上传:
上传成功:
上传失败:
项目结构:
开发步骤:
1.新建Struts2Upload项目工程,导入struts2需要的jar包(项目结构图中),配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
2.新建FileUploadAction.java
package action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
* Struts2文件上传,支持多个文件
*
* @author Administrator
*
*/
@SuppressWarnings("unused")
public class FileUploadAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private File[] upload;// 文件 必须与上传的input的name一致
private String[] uploadFileName;// 文件名 **FileName
private String[] uploadContentType;// 文件类型 **ContentType
private String allowTypes;//允许上传的文件类型
private String savePath;// 文件上传保存目录
private int saveCount;// 上传保存成功的个数
private String msg;//返回的提示信息
public String fileUpload() {
String realPath = ServletActionContext.getServletContext()
.getRealPath(savePath);
File file = new File(realPath);
if (!file.exists()) {
file.mkdirs();
}
try {
if (upload != null && upload.length > 0) {
//校验是否存在不允许上传的文件类型
if(!filterTypes(allowTypes,uploadContentType)){
msg = "存在不允许的文件类型";
return "upload";
}
saveCount = fileCopy(upload, uploadFileName, realPath);
//saveCount = fileCopy2(upload, uploadFileName, realPath);
msg = "恭喜你,上传成功啦";
}
} catch (Exception e) {
e.printStackTrace();
}
return SUCCESS;
}
/**
* 使用文件流保存文件
* @param files 文件数组
* @param fileNames 文件名数组
* @param realPath 保存路径
* @return 保存成功的文件个数
* @throws Exception
*/
private int fileCopy(File[] files, String[] fileNames, String realPath)
throws Exception {
FileInputStream in = null;
FileOutputStream out = null;
int count = 0;
for (int i = 0; i < files.length; i++) {
System.out.println("文件名:" + fileNames[i] +" 文件类型:" + uploadContentType[i]);
in = new FileInputStream(files[i]);
out = new FileOutputStream(realPath + File.separator + fileNames[i]);
byte[] b = new byte[1024];
int len = 0;
while ((len = in.read(b)) != -1) {
out.write(b, 0, len);
}
count++;
}
in.close();
out.close();
return count;
}
/**
* 使用org.apache.commons.io.FileUtils工具类保存
* @param files 文件数组
* @param fileNames 文件名数组
* @param realPath 保存路径
* @return 保存成功的文件个数
* @throws Exception
*/
private int fileCopy2(File[] files, String[] fileNames, String realPath)
throws Exception {
int count = 0;
for (int i = 0; i < files.length; i++) {
FileUtils.copyFile(files[i], new File(realPath
+ File.separator
+ fileNames[i]));
count++;
}
return count;
}
/**
* 手动过滤,也可以通过配置struts2的fileUpload拦截器过滤
* @param types 允许上传的文件类型字符串(逗号分隔)
* @param allTypes 上传文件的类型数组
* @return true:符合 false:不符合
*/
private boolean filterTypes(String types,String[] allTypes){
if(types==null && "".equals(types)){
return true;
}
for(String str : allTypes){
if(!types.contains(str)){
return false;
}
}
return true;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getAllowTypes() {
return allowTypes;
}
public void setAllowTypes(String allowTypes) {
this.allowTypes = allowTypes;
}
public int getSaveCount() {
return saveCount;
}
public void setSaveCount(int saveCount) {
this.saveCount = saveCount;
}
public String[] getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String[] uploadFileName){
this.uploadFileName = uploadFileName;
}
public String[] getUploadContentType() {
return uploadContentType;
}
public void setUploadContentType(String[] uploadContentType) {
this.uploadContentType = uploadContentType;
}
public String getSavePath() {
return savePath;
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public File[] getUpload() {
return upload;
}
public void setUpload(File[] upload) {
this.upload = upload;
}
}
3.配置struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!--将默认上传的文件大小改为500MB -->
<constant name="struts.multipart.maxSize" value="524288000"/>
<!--编码-->
<constant name="struts.i18n.encoding" value="UTF-8" />
<!--开发模式-->
<constant name="struts.devMode" value="true" />
<package name="default" extends="json-default" namespace="/">
<action name="fileUploadAction" class="action.FileUploadAction" method="fileUpload">
<!-- 配置文件保存路径 -->
<param name="savePath">/upload</param>
<!-- 配置允许上传的文件类型-->
<param name="allowTypes">image/png,image/gif,image/jpg,image/jpeg</param>
<result name="success">/success.jsp</result>
<result name="upload">/upload.jsp</result>
</action>
</package>
</struts>
4.新建upload.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
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%>">
<title>文件上传</title>
</head>
<body>
<span style="color:red">${msg}</span><br/>
<fieldset style="width: 50%;border-color: #99CCCC">
<legend>图片上传</legend>
<form action="fileUploadAction.action" enctype="multipart/form-data" method="post">
<input type="file" name="upload" multiple="multiple"/>
<input type="submit" value="上传"><br/><br/>
<span style="color:red;font-size:10px">图片格式仅限jpeg、jpg、png</span>
</form>
<!--
如果浏览器不支持 multiple="multiple" 则使用多个input的形式
<form action="fileUploadAction.action" enctype="multipart/form-data" method="post">
<input type="file" name="upload"/><br/>
<input type="file" name="upload" /><br/>
<input type="file" name="upload" /><br/>
<input type="submit" value="上传"><br/><br/>
<span style="color:red;font-size:10px">图片格式仅限jpeg、jpg、png</span>
</form>
-->
</fieldset>
</body>
</html>
5.新建success.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%
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%>">
<title>文件上传</title>
</head>
<body>
<span style="color:red;font-size:20px">${msg}</span><br/>
<!-- 个数:${saveCount}<br/> -->
<c:forEach items="${uploadFileName}" var="fileName">
<img style="width: 200px;margin-bottom: 5px;margin-left: 200px"
src="<%=basePath%>/${savePath}/${fileName}"><br/>
</c:forEach>
</body>
</html>
6.部署项目到tomcat,浏览器访问http://localhost:8080/Struts2Upload/upload.jsp
转载请注明出处:http://blog.csdn.net/u012219290