struts2 实现文件下载功能:

1.解决文件名编码问题。

## Action中:

// 返回编码后的文件名
public String getDownloadFilename() throws IOException {
if (user == null || user.getFilename() == null) {
return null;
}
return encodeDownloadFilename(user.getFilename(), ServletActionContext.getRequest().getHeader(“user-agent”));
}

/**
* 下载文件时,针对不同浏览器,进行附件名的编码
*
* @param filename
* 下载文件名
* @param agent
* 客户端浏览器
* @return 编码后的下载附件名
* @throws IOException
*/
public String encodeDownloadFilename(String filename, String agent) throws IOException {
if (agent.contains(“Firefox”)) { // 火狐浏览器
filename = “=?UTF-8?B?” + new BASE64Encoder().encode(filename.getBytes(“utf-8”)) + “?=”;
} else { // IE及其他浏览器
filename = URLEncoder.encode(filename, “utf-8″);
}
return filename;
}
//返回文件流
public InputStream getInputStream() throws IOException{
if(user==null||user.getPath()==null){
return null;
}
File file = new File(user.getPath());
System.out.println(file+””);
return new FileInputStream(file);
}

## struts.xml

<!–下载 –>
<result name=”download_success” type=”stream”>
<!– 下载流 attachment :下载时会打开下载框 fileName=”${fileName}” :在这定义的名字是一个动态的,该名字是显示在下载框上的文件名字 –>
<param name=”contentType”>${contentType}</param>
<param name=”contentDisposition”>attachment;filename=${downloadFilename}</param>
<param name=”inputStream”>${inputStream}</param>
</result>

Advertisements
struts2 实现文件下载功能:

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s