转帖地址忘了
/**
* 下载文件
* @param response javax.servlet.http.HttpServletResponse
*/
@RequestMapping("/downloadFile")
public void downloadFile(HttpServletResponse response) {
String fileName = "D://test.txt";
File file = new File(fileName);
FileInputStream in = null;
InputStreamReader isr = null;
response.reset();
response.addHeader("Content-Disposition", "attachment;filename="
+ file.getName());
response.addHeader("Content-Length", "" + file.length());
response.setContentType("bin");
OutputStream toClient;
// 文件不存在时跳出
if (!file.exists()) {
return;
}
String s = null;
StringBuilder sb = new StringBuilder();
try {
in = new FileInputStream(file);
isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
while ((s = br.readLine()) != null) {
sb.append(s);
sb.append("/r/n"); // 换行符
}
isr.close();
in.close();
toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(sb.toString().getBytes());
toClient.flush();
toClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}