一 、 使用基于common-upload实现的struts2文件上传功能。
1、fileUpload拦截器---》在struts-dedault.xml
在struts-dedault.xml中有默认的fileUpload拦截器
2、 利用表单实现上传页面
<%@ 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>Insert title here</title>
</head>
<body>
<form action="/namespace/uploadAction.action" method="post"
enctype="multipart/form-data">
文件名称:<input type="text" name="fileName"> 文件:<input type="file"
name="myFile"><br> <input type="submit" value="提交">
</form>
</body>
</html>
3、实现文件上传的action
package lee;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
/**
* 实现文件保存到本地
*/
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private String fileName;
private String myFile;
@Override
public String execute() throws Exception {
OutputStream outputStream = null;
InputStream inputStream = null;
// 存入本地,也可以自及操作存入数据库
outputStream = new FileOutputStream(new File("e:/temp/" + fileName));
byte[] bs = new byte[1024];
// 将上传的文件输出到output中
inputStream = new FileInputStream(new File(myFile));
// 循环写入
int len;
while ((len = inputStream.read(bs)) > 0) {
outputStream.write(bs, 0, len);
}
outputStream.close();
inputStream.close();
return SUCCESS;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getMyFile() {
return myFile;
}
public void setMyFile(String myFile) {
this.myFile = myFile;
}
}
4、配置struts2
<action name="uploadAction" class="lee.UploadAction">
<result>/jsp/welcom.jsp</result>
</action>
5、限制文件大小和类型
- allowedTypes: 指定文件的类型
- maximumsize 指定文件上传最大
- allowedExtensions:指定文件扩展名
二、文件下载
利用struts2 的<result-type name= stream...解决
利用action中的getDownLoadFileName方法,OGNL访问getter方法获取文件名。。。
<action name="downloadAction" class="lee.DownLoadAction"> <result type="stream"> <param name="contentDisposition"> attachment;filename=${downLoadFileName}</param> </result> </action>
2、action写法import java.io.InputStream; import com.opensymphony.xwork2.ActionSupport; /** * 下载文件的Action,不需要实现excute()方法 直接使用返回InputStream的getInputStream() * * @author wu * */ public class DownLoadAction extends ActionSupport { private static final long serialVersionUID = 1L; public String getDownLoadFileName() { return "test.doc"; } public InputStream getInputStream() throws Exception { File file = new File("e:/temp/测试.doc"); return new FileInputStream(file); } }
3、jsp<a href="/downloadAction.action">下载文件</a>