之前也写过Struts2的文件上传,可以参考一下:
Struts2文件上传(一)
Struts2文件上传(二)-文件上传拦截器
在这里,重新整理一下,介绍一下,上传与下载,首先是单文件上传
文件上传的话,需要:
1.一个上传文件的表单
2.一个做处理的Action
3.当然struts.xml不可少
1.upload.jsp
<%@ 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>
<h3>1.单文件上传</h3>
<form action="file/common!upload" method="post" enctype="multipart/form-data">
请选择文件:<input type="file" name="sgFile"><br/>
<input type="submit" value="上传">
</form>
</body>
</html>
2.FileAction
package com.deppon.demo.struts.action;
import java.io.File;
import org.apache.struts2.ServletActionContext;
import com.deppon.demo.struts.util.FileUtil;
import com.opensymphony.xwork2.ActionSupport;
public class FileAction extends ActionSupport {
private static final long serialVersionUID = 3130770865205322375L;
/**
* 这里是有一个对应关系的
*/
private File sgFile;//xxx
private String sgFileFileName;//xxxFileName
private String sgFileContentType;//xxxContentType
public File getSgFile() {
return sgFile;
}
public void setSgFile(File sgFile) {
this.sgFile = sgFile;
}
public String getSgFileFileName() {
return sgFileFileName;
}
public void setSgFileFileName(String sgFileFileName) {
this.sgFileFileName = sgFileFileName;
}
public String getSgFileContentType() {
return sgFileContentType;
}
public void setSgFileContentType(String sgFileContentType) {
this.sgFileContentType = sgFileContentType;
}
/**
* 单文件上传
* @return
*/
public String upload() {
System.out.println("sgFileFileName->" + sgFileFileName);//可以获取文件的名字
System.out.println("sgFileContentType->" + sgFileContentType);
/*
* 这里获取项目的绝对路径,有2种方法
* 目的都是获取ServletContext,然后,通过getRealPath(),来获取路径。
*
*/
//1.使用ActionContext
// ActionContext ac = ActionContext.getContext();
// ServletContext sc = (ServletContext) ac.get(ServletActionContext.SERVLET_CONTEXT);
// String path = sc.getRealPath("/data");
//2.使用ServletActionContext
StringBuilder path = new StringBuilder(ServletActionContext.getServletContext().getRealPath("/data"));
path.append(File.separator);
path.append(sgFileFileName);
FileUtil.save(sgFile, path.toString());
return SUCCESS;
}
}
3.struts.xml
<?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.i18n.encoding" value="utf-8"></constant>
<constant name="struts.custom.i18n.resources" value="message"></constant>
<constant name="struts.multipart.maxSize" value="20971520"/>
<constant name="struts.devMode" value="true" />
<package name="p_file" namespace="/file" extends="struts-default">
<action name="common" class="com.deppon.demo.struts.action.FileAction">
<result name="success" type="redirect">/upload_success.jsp</result>
</action>
</package>
</struts>