struts.xml:
<result name="output" type="stream">
<param name="inputName">inputStream</param>
<param name="contentType">application/octet-stream</param>
<param name="contentCharSet">UTF-8</param>
<param name="contentDisposition">attachment;filename="${downloadFileName}"</param>
<param name="bufferSize">4096</param>
</result>
action:
private String downloadFileName;//客户端下载文件显示的文件名
private InputStream inputStream4Download;//下载所需的inputStream
/**
* 向客户端输出文件
* @param downloadFileName 客户端将保存将显示的名称
* @param filePath 要输出文件的磁盘路径
*/
public String output(String downloadFileName,String filePath){
try {
this.downloadFileName = downloadFileName;
inputStream4Download = new FileInputStream(new File(filePath));
} catch (Exception e) {
log.info("输出文件失败,文件未找到:", e);
inputStream4Download = new ByteArrayInputStream("文件未找到,请联系管理员".getBytes());
this.downloadFileName = "下载异常.txt";
}
return "output";
}
public InputStream getInputStream4Download() throws FileNotFoundException {
return inputStream4Download;
}
/**
* struts的attachment;filename="${downloadFileName}"通过此方法取得downloadFileName
* @return
*/
public String getDownloadFileName() {
HttpServletRequest request = ServletActionContext.getRequest();
String agent = request.getHeader("User-Agent");
try {//根据不同浏览器进行转码解决文件名乱码
if (null != agent) {
agent = agent.toLowerCase();
if (agent.indexOf("firefox") != -1) {
this.downloadFileName = new String(downloadFileName.getBytes(), "iso8859-1");
} else {
this.downloadFileName = URLEncoder.encode(downloadFileName, "UTF-8");
}
} else {
this.downloadFileName = URLEncoder.encode(downloadFileName, "UTF-8");
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e); // won't happen
}
return downloadFileName;
}
/**
* 下载
* @return
* @throws UnsupportedEncodingException
*/
public String download(){
return output(displayName,filepath);
}