java struts2 的 文件下载

jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

  <a href="download.do">点击下载</a>

</body>
</html>

struts.xml

<!-- 下载文件 -->
<action name="download" class="com.hdsx.gzgispf.controller.FileDownloadAction">
  <result name="success" type="stream">
  <param name="contentType">text/plain</param>
  <param name="inputName">inputStream</param>
  <param name="contentDisposition">attachment;filename="${downloadFileName}"</param>
  <param name="bufferSize">4096</param>
  </result>
</action>

com.hdsx.gzgispf.controller.FileDownloadAction  :

/**
* 处理带中文的文件名(可设置下载文件名)
* @return
*/
public String getDownloadFileName() {
fileName="struts2的下载文件.doc";
String downloadFileName = null;
try {
downloadFileName = fileName;
downloadFileName = URLEncoder.encode(downloadFileName,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return downloadFileName;
}

/**
* 获取下载流
* @return
*/
public InputStream getInputStream () {

String context="";
String str="";
InputStream in=null;

//获取当前项目的路径    被下载的文件名为:111.doc
String path = ServletActionContext.getRequest().getSession().getServletContext().getRealPath("/")+"111.doc";

try {
File someFile = new File(path );
FileInputStream fis = new FileInputStream(someFile);
InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
BufferedReader br = new BufferedReader(isr);

while((str=br.readLine())!=null){
context+=str+"\n";
}
in=new ByteArrayInputStream(context.getBytes());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return in ;

}

public String execute(){
return "success";
}

上一篇:教你如何查看CAD文件是哪个版本的来自http://blog.sina.com.cn/s/blog_4c9fa4dd0101il1v.html


下一篇:C#.Net参数