public static void downFile(String filepath,String fileName,HttpServletResponse response) {
FileInputStream fileinputstream = null;
PrintWriter out = null;
try {
response.reset();
// File file = new File(filepath +EmoneyConstants.MARK_SLASH+ fileName);
File file = new File(filepath + fileName);
if (file.exists()) {
response.setContentType("application/x-download");// 设置response内容的类型
response.setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));// 设置头部信息
fileinputstream = new FileInputStream(file);
out = response.getWriter();
int i;
//开始向网络传输文件流
while ((i = fileinputstream.read()) != -1) {
out.write(i);
}
} else{
log.error("FileUtils downFile File not found!!!!");
}
if(out != null) out.flush();
if(out != null) out.close();
if(fileinputstream != null) fileinputstream.close();
} catch (Exception e) {
log.error("FileUtils downFile Exception " + e);
}finally{
try{
if(out != null) out.close();
if(fileinputstream != null)fileinputstream.close();
} catch (IOException ee) {
log.error(" download failed !! " + ee);
}
}
}
java 下载文件
本文介绍了一个使用Java实现的文件下载方法。该方法通过输入文件路径和名称,利用HTTP响应将指定文件下载到客户端。文中详细展示了如何设置HTTP响应头、处理文件流以及异常情况。

被折叠的 条评论
为什么被折叠?



