公司项目中要用到利用Excel批量导入数据和并且有一个Excel模板下载功能,数据导入倒没什么问题,网上
例子一大推,下载的时候一开始后缀名一直是action,经过很久才搞定,
一、action的xml配置
<!--文件下载 -->
<action name="downloadOBS" class="cn.fulong.omp.web.action.ServiceProcessManagerAction" method="downloadOBS">
<param name="directory"></param><!-- 一定要是action中的成员变量,并提供set和get方法 -->
<result name="success" type="stream">
<param name="contentType">text/plain</param>
<param name="inputName">inputStream</param><!-- 指定返回流的方法为getInputStream()-->
<param name="contentDisposition">
attachment;filename="${filename}"<!-- filename为下载后的文件名,一定要是action中的成员变量,并提供set和get方法,这步决定了你的文件名的后缀,后缀名为action时,一定是在这里错了-->
</param>
<param name="bufferSize">2014</param>
</result>
</action>
二、action的写法
private String filename;
private String directory;
public String downloadOBS() {
return SUCCESS;
}
public InputStream getInputStream() throws IOException {
String separator = java.io.File.separator;
String fileName = "";
// 导入线下服务成果的Excel表格数据表模板文件名称
filename = "服务成果.xlsx";
try {
filename = new String(filename.getBytes(), "ISO-8859-1");
//这里要转码,如果是文件名是中文就会乱码,文件名是英文的话,这步不写也没问题
fileName = Platform.getInstance().getRealPath() + separator
+ "file" + separator + "fdsasaggg.xlsx";
//拿到文件名,该文件放在根路径下的file文件夹下
System.out.println(fileName);
InputStream is = new FileInputStream(fileName);
//拿到文件流
if (is != null) {
return is;
} else {
return null;
}
} catch (Exception e) {
return null;
}
}
public get....
public set....
分析:
问题一:下载后的文件名称为.action
刚接触Struts2下载的孩子很容易就出现下载后的文件名为.action的情况,我当时是因为没有理清文件下载的流程,被filename和fileName给搞乱了,filename是指下载后的文件名,fileName是指项目中文件的名称(绝对路径),作用是来生成文件流的。
问题二:中文乱码问题,下载后的文件只出现文件后缀名
加上filename = new String(filename.getBytes(), "ISO-8859-1"); 因为表单提交的时候默认用的编码是ISO-8859-1