Java 实现下载
效果就是点击就可以下载到本机。
- 前台代码示例
- 后台代码示例
前台代码示例
<a target='_self' href='../downTask/downloadFileToLocal?fileName=59.csv' >
后台代码示例
@RequestMapping(value = "/downloadFileToLocal", method = RequestMethod.GET)
public void downloadFileToLocal(String fileName,HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName="
+ fileName);
OutputStream os = response.getOutputStream();
try {
String path = Helper.getAppPath();
log.debug("========="+path);
InputStream inputStream = new FileInputStream(new File(path
+ File.separator + fileName));
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
os.close();
}
}
注:我这个框架是用的SpringMVC,自行修改吧。
Code is read far more than it's written