文件上传
Action类
/**
* 文件上传Action
*
* @author wangn
*
*/
public class FileUPDown extends ActionSupport {
private File files;
private String filesFileName;
private String FilesContentType;
public void setFiles(File files) {
this.files = files;
}
public void setFilesFileName(String filesFileName) {
this.filesFileName = filesFileName;
}
public void setFilesContentType(String filesContentType) {
this.FilesContentType = filesContentType;
}
@Override
public String execute() throws Exception {
String path = "E://temp";
File file = new File(path, filesFileName);
FileUtils.copyFile(files, file);
return SUCCESS;
}
}
struts.xml
<struts>
<constant name="struts.multipart.maxSize" value="31457280"/>
<package name="file" extends="struts-default">
<action name="file" class="com.ning.file.FileUPDown" method="execute">
<interceptor-ref name="defaultStack">
<param name="fileUpload.allowedExtensions">txt,jpg,jar</param>
</interceptor-ref>
<result name="success">success.jsp</result>
<result name="input">fileerror.jsp</result>
</action>
</package>
</struts>
jsp页面
<form action="<%=basePath%>file" method="post" enctype="multipart/form-data">
<input type="file" name="files">
<input type="submit" value="提交">
</form>
文件下载
Action类
/**
* 下载Action
* @author wangn
*
*/
public class Down extends ActionSupport {
private String fileName;
/**
* 从GET方法提交的请求封装给fileName属性
* @param fileName 传入的文件名
*/
public void setFileName(String fileName) {
try {
fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
this.fileName = fileName;
}
/**
*
* @return result name
*/
public String download() {
return "download";
}
/**
* 在file.xml中 param name="inputName">attrInputStream
* @return 文件流
*/
public InputStream getAttrInputStream(){
return ServletActionContext.getServletContext().getResourceAsStream("/upload/" + fileName);
}
/**
* 下载显示的文件名(浏览器显示的文件名)
* @return 文件名
*/
public String getDownFileName() {
try {
fileName = URLEncoder.encode(fileName, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return fileName;
}
}
/**
输入流转输出流实现:例如POI实现下载excel
ByteArrayOutputStream baos=new ByteArrayOutputStream();
workbook.write(baos);
ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
return swapStream;
**/
struts.xml
<package name="down" extends="struts-default">
<action name="down" class="com.ning.file.Down" method="download">
<result name="download" type="stream">
<param name="contentType">application/octet-stream</param>
<param name="inputName">attrInputStream</param>
<param name="contentDisposition">attachment;filename=${downFileName}</param>
<param name="bufferSize">1024</param>
</result>
</action>
</package>
jsp页面
<body>
<a href="<%=basePath%>down?fileName=a.txt">下载</a>
</body>