当前位置: 代码迷 >> Java Web开发 >> springMVC怎么实现文件的下载
  详细解决方案

springMVC怎么实现文件的下载

热度:3112   发布时间:2016-04-11 00:08:26.0
springMVC如何实现文件的下载?
我的数据库里一张表保存三个参数,分别是:id,name(文件名),path(在服务器上的文件路径);
此时对应的服务器上有对应的文件。
我要把它下载到本地计算机上,不用struts2,下载代码怎么写,controller应该怎么写?如何能实现和struts2下载功能一样的效果。
刚刚接触springMVC,以前都是用struts2的,现在用springMVC就不会了,哪位大哥给指点一下,最好能附上代码,谢谢,分会全部奉上
springmvc 服务器 计算机

------解决方案--------------------
这个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();   
  }   
  相关解决方案