因项目需要,需要用到文件的上传与下载,找了n久的资料最终用struts2本身的上传来实现,直接上代码:
在struts.xml文件中配置:
<action name="addUploadFile" class="UploadFileAction" method="addUploadFile">
<param name="inputPath">d:\uploadfile</param>
<result name="input">/index.jsp</result>
</action>
inputPath: 文件要保存的路径
//上传方法
public String upload(File myFile,String fileName) {
File imageFile = new File(inputPath); //得到流的目录
// 目录已存在创建文件夹
if (!imageFile.exists()) {
imageFile.mkdir();
}
File imageFile2 = new File( inputPath + "\\" + fileName);
copy(myFile, imageFile2);
return fileName.toString();
}
//定义文件复制方法
private void copy(File src, File dst) {
try {
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(src),
BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dst),
BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
for (int byteRead = 0; (byteRead = in.read(buffer)) > 0;) {
out.write(buffer, 0, byteRead);
}
} finally {
if (null != in) {
in.close();
}
if (null != out) {
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
最后在web.xml文件中配置过滤器:
<display-name> Struts 2 Fileupload </display-name>
<filter >
<filter-name> struts-cleanup </filter-name>
<filter-class>
org.apache.struts2.dispatcher.ActionContextCleanUp
</filter-class>
</filter >
<filter-mapping>
<filter-name> struts-cleanup </filter-name >
<url-pattern> /* </url-pattern >
</filter-mapping>
实现文件的上传
下载:
<!-- 配置文件下载的action -->
<action name="downloadUploadFile" class="UploadFileAction" method="downloadUploadFile">
<!--下载文件的目录,若不在这个目录下则拒绝下载以保障安全,这点在action类中实现 -->
<param name="inputPath">d:\uploadfile</param>
<result name="down" type="stream">
<param name="contentType">application/octet-stream</param>
<param name="inputName">inputStream</param>
<!--动态获取文件名,这点很用实用价值!-->
<!-- <param name="contentDisposition">attachment;filename="${fileName}"</param>-->
<param name="bufferSize">4096</param>
</result>
</action>
inputPath: 为要下载的目录,和上传的目录保持一致
down:在struts2中会返回一个down的字符串
contentType: 流格式
inputName: 获取当前的流
contentDisposition:可以动态获取文件名(但是,如果写在这里不支持中文,我是写在了代码中)
bufferSize:缓冲区大不
java 代码:
public InputStream getInputStream(){ //此方法与上面的配置文件中的inputStream相对应
String url = inputPath + "\\" + fileName;
try {
if(fileName != null){
return new FileInputStream(new File(url));
}
} catch (Exception e) {
e.printStackTrace();
logger.error("Exception",e);
}
return null;
}
//文件下载
public String downloadUploadFile() throws Exception {
HttpServletResponse response = ServletActionContext.getResponse();
response.setHeader( "Content-Disposition", "attachment;filename="+new String(fileName.getBytes("gb2312"), "ISO8859-1" ) ); //避免了中文乱码
return "down";
}
当前,在上面中inputPath和fileName要写相应的get和set方法,相信学过struts2的人一定明白的
学习随笔,暂记于此