jsp页面
<form action="<c:url value='/uploadFile.do'/>" name="form1" method="post"
enctype="multipart/form-data" >
<input name="doc" id= "doc" type="file" />
</form>
其中: enctype="multipart/form-data" 必备
struts.xml配置:
<action name="download" class="uploadandDownloadRiskReportAction">
<param name="fileName">此入填写下提示的名称,比如:测试报告.doc</param>
<result name="success" type="stream">
<param name="contentType">application/octet-stream;charset=ISO8859-1</param>
<param name="inputName">inputStream</param>
<!-- 使用经过转码的文件名作为下载文件名,downloadFileName属性 对应action类中的方法 getDownloadFileName() -->
<param name="contentDisposition">attachment;filename="${downloadFileName}"</param>
<param name="bufferSize">4096</param>
</result>
<result name="error">/app/report/annualReportOfTheLegalRisks/error.jsp</result> </action>
JAVA 代码:
private String fileName;// 初始的通过param指定的文件名属性 set/get省略
public InputStream getInputStream() {
//下载地址
String inputPath = this.getRequest().getRealPath("/")
+ "docs\\annualreport\\template\\测试报告.doc";
logger.info("inputPath ***********" + inputPath);
InputStream stream = null;
try {
stream = new java.io.FileInputStream(inputPath);
} catch (FileNotFoundException e) {
}catch(IOException ie){
}
return stream;
}
public String execute(){
logger.info("****************************会先*进入了execute 方法*******************************");
String inputPath = this.getRequest().getRealPath("/")+PropertiesUtil.getInstance().getProperty("riskReportFilePath");
File file = new File(inputPath);
if(file.exists()){
return SUCCESS;
}else{
this.errorStr ="未找到文件";
this.returnUrl="/uploadandDownload/init.do";
return ERROR;
}
}
public String getDownloadFileName() {
String downFileName = fileName;
try {
downFileName = new String(downFileName.getBytes(), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
}
return downFileName;
}
java中的两个方法必备。
具体查看资料:http://berry0606.iteye.com/blog/570239
本文介绍如何使用Struts2框架实现文件的上传与下载功能。详细展示了JSP页面的表单设置、Struts配置文件中对于下载Action的配置方式,以及必需的Java代码实现。包括了设置文件类型、下载文件名的转码处理等关键步骤。
332

被折叠的 条评论
为什么被折叠?



