SSH Struts2上传文件
Struts2 上传文件
上传文件在一个系统当中是一个很常用的功能,也是一个比较重要的功能。今天我们就一起来学习一下Struts2如何上传文件。今天讲的上传文件的方式有三种:
- 1以字节为单位传输文件;
- 2Struts2封装的一种方式;
- 3以字符的方式传输文件。
其实这三种方式都差不多,都是将文件先从客户端一临时文件的形式,传输到服务器的临时文件夹下,然后在将该临时文件复制到我们要上传的目录。另外,有一个需要注意,就是上传过程中产生的这些临时文件,Struts2不会自动清理,所以我们需要手动清理临时文件,这一个下面的代码中有提到。
用Action来完成我们上传的核心功能:
package com.action;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Map;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
private File upload;
private String uploadFileName;
private String uploadContentType;
private long maximumSize;
private String allowedTypes;
public File getUpload() {
return upload;
}
public void setUpload(File upload) {
this.upload = upload;
}
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 long getMaximumSize() {
return maximumSize;
}
public void setMaximumSize(long maximumSize) {
this.maximumSize = maximumSize;
}
public String getAllowedTypes() {
return allowedTypes;
}
public void setAllowedTypes(String allowedTypes) {
this.allowedTypes = allowedTypes;
}
@Override
public String execute() throws Exception {
File uploadFile = new File(ServletActionContext.getServletContext().getRealPath("upload"));
if(!uploadFile.exists()) {
uploadFile.mkdir();
}
//验证文件大小及格式
if (maximumSize < upload.length()) {
return "error";
}
boolean flag =false;
String[] allowedTypesStr = allowedTypes.split(",");
for (int i = 0; i < allowedTypesStr.length; i++) {
if (uploadContentType.equals(allowedTypesStr[i])) {
flag = true;
}
}
if (flag == false) {
Map request = (Map) ActionContext.getContext().get("request");
request.put("errorMassage", "文件类型不合法!");
System.out.println(request.toString());
return "error";
}
//第一种上传方式
// FileInputStream input = new FileInputStream(upload);
// FileOutputStream out = new FileOutputStream(uploadFile +"//"+ uploadFileName);
// try {
// byte[] b =new byte[1024];
// int i = 0;
// while ((i=input.read(b))>0) {
// out.write(b, 0, i);
// }
// } catch (Exception e) {
// e.printStackTrace();
// } finally {
// //关闭输入、输出流
// input.close();
// out.close();
// //删除临时文件
// upload.delete();
// }
//第二种上传方式
// FileUtils.copyFile(upload, new File(uploadFile+"\\"+uploadFileName));
// //删除临时文件
// upload.delete();
//第三种上传方式
BufferedReader bReader = new BufferedReader(new InputStreamReader(new FileInputStream(upload)));
BufferedWriter bWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(uploadFile+"\\"+ uploadFileName)));
try {
char [] c =new char[1024];
int i = 0;
while ((i = bReader.read(c)) > 0) {
bWriter.write(c, 0, i);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
bReader.close();
bWriter.close();
//删除临时文件
upload.delete();
}
return "success";
}
}
在Struts.xml文件中配置我们的Action:
<?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.action.extension" value=","></constant>
<!-- 上传文件最大限制(如果为多文件上传,则为多个文件的总大小) -->
<constant name="struts.multipart.maxSize" value="40000000"></constant>
<!-- 存放上传文件的临时目录 -->
<constant name="struts.multipart.saveDir" value="D:\\temp"></constant>
<package name="upload" namespace="/file" extends="struts-default">
<action name="upLoad" class="com.action.UploadAction">
<result name="success">/success.jsp</result>
<result name="error" >/error.jsp</result>
<result name = "input" type ="redirect">/index.jsp</result>
<param name="maximumSize ">1000000</param>
<param name="allowedTypes">application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,text/plain</param>
<!--用struts拦截器限制上传文件大小及类型
<interceptor-ref name="fileUpload">
单个文件的大小
<param name="maximumSize ">1000000</param>
<param name="allowedTypes">application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,text/plain</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
-->
</action>
</package>
</struts>
文件上传的页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上传文件</title>
</head>
<body>
<!-- enctype="multipart/form-data"不对字符编码。在使用包含文件上传控件的表单时,必须使用该值。 -->
<form action="file/upLoad" method="post" enctype="multipart/form-data">
<input name="upload" type="file">
<input name="btnUpload" type="submit" value="上传">
</form>
</body>
</html>
上传文件之前,通常要判断一下文件的大小及类型,上面有两种方式来验证,一种是在Action里验证,一种是通过Struts2的拦截器验证。两者选其一,选择一个把另一个注释掉即可。
另外,还有一个需要注意:上传文件页面中form的enctype属性值,一定要设置成"multipart/form-data",否则就会出错。
OK,今天上传文件就向大家介绍到这里,我们下篇博客再见!