• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
冰花ぃ雪魄

导航

  • 博客园
  • 首页
  • 新随笔
  • 联系
  • 订阅 订阅
  • 管理

公告

 

java文件下载

这个SpringMVC没什么关系吧,我在jsp中做过一个图片的下载,你可能要修改下代码

response.setContentType("application/x-download");   
 //application.getRealPath("/main/mvplayer/CapSetup.msi");获取的物理路径   
 String filedownload = request.getRealPath("/")+"/organization/img/"+"组织架构图.png";   
   String filedisplay = "组织架构图.png";   
    filedisplay = URLEncoder.encode(filedisplay,"UTF-8");   
    response.addHeader("Content-Disposition","attachment;filename=" + filedisplay);   
  
  java.io.OutputStream outp = null;   
  java.io.FileInputStream in = null;   
  try   
  {   
  outp = response.getOutputStream();   
  in = new java.io.FileInputStream(filedownload);   
  
  byte[] b = new byte[1024];   
  int i = 0;   
  
  while((i = in.read(b)) > 0)   
  {   
   outp.write(b, 0, i);   
  }   
outp.flush();   
//要加以下两句话,否则会报错   
//java.lang.IllegalStateException: getOutputStream() has already been called for this respons
out.clear();   
out = pageContext.pushBody();   
}   
  catch(Exception e)   
  {   
  System.out.println("Error!");   
  e.printStackTrace();   
  }   
  finally   
  {   
  if(in != null)   
  {   
  in.close();   
  in = null;   
  } 
  
  if(in != null)   
  {   
  in.close();   
  in = null;   
  }  
  }   


这些在网上找也很好找的
 
对我有用[0] 丢个板砖[0] 引用 | 举报 | 管理

kuailexiaobuding
关注
kuailexiaobuding
kuailexiaobuding
本版等级:T1
 
#3 得分:20 回复于: 2013-09-23 09:57:16
//下载方法
private void downloadFile(File file){
String fileName = file.getName();
try {
fileName = URLEncoder.encode(fileName, "UTF-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
contextPvd.getResponse().setContentType("application/zip");
contextPvd.getResponse().addHeader("Content-Disposition", "attachment;filename=" + fileName);
OutputStream outp = null;
FileInputStream in = null;
try {
outp = contextPvd.getResponse().getOutputStream();
in = new FileInputStream(file);
byte[] b = new byte[1024];
int i = 0;

while ((i = in.read(b)) > 0) {
outp.write(b, 0, i);
}
outp.flush();
} catch (Exception e) {
//log.error("", e);
} finally {
if (in != null) {
try {
in.close();
in = null;
} catch (IOException e) {
e.printStackTrace();
}
}
if (outp != null) {
try {
outp.close();
outp = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
posted on 2016-09-06 10:20  冰花ぃ雪魄  阅读(159)  评论(0)    收藏  举报
 
刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3