java下载文件

/**
* 下载文件
*/
@SuppressWarnings("deprecation")
public ActionForward doDownload(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
FlowForm fileForm = (FlowForm) form;
OutputStream toClient = null;
try {
//测试--设置为固定路径
String path = request.getRealPath("/") + "upload\\" + fileForm.getFileName();
File file = new File(path);
String filename = file.getName();

// 取得文件的扩展名
String ext = filename.substring(filename.lastIndexOf(".") + 1)
.toUpperCase();

InputStream fis = null;
try{
fis = new BufferedInputStream(new FileInputStream(path));
}catch(FileNotFoundException e){
e.printStackTrace();
System.out.println("系统没有找到指定文件");
}
if(fis==null){
response.getWriter().print("<script>alert('系统没有找到指定文件!');history.go(-1);</script>");
return null;
}
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();

response.reset();
response.addHeader("Content-Disposition", "attachment;filename="
+ new String(filename.getBytes()));
response.addHeader("Content-Length", "" + file.length()); // 设置返回的文件类型
toClient = new BufferedOutputStream(response
.getOutputStream()); // 得到向客户端输出二进制数据的对象
// 根据扩展名声称客户端浏览器mime类型
if (ext.equals("DOC"))
response.setContentType("application/msword");
else
response.setContentType("application/octet-stream"); // 设置返回的文件类型
try{
if(toClient != null){
toClient.write(buffer); // 输出数据
toClient.flush();
}
}catch(Exception e){
e.printStackTrace();
System.out.println("用户取消下载文件...");
}
} catch (IOException ex) {
ex.printStackTrace();
} finally{
try {
if(toClient!=null){
toClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}

你可能感兴趣的:(java,浏览器,ext,Go)