文件下载

下载 在action中

//读取数据库中保存的文件名称

String fileName = data.getFileName();
   response.setContentType("application/msword");
   response.setHeader("Content-disposition","attachment; filename="+fileName);
   ServletContext context = servlet.getServletContext();
   String filePath = context.getRealPath("wenjian/");
      BufferedInputStream bis = null;
      BufferedOutputStream bos = null;
      String path = filePath + "\\" +fileName;
      try {
          bis = new BufferedInputStream(new FileInputStream(path));
          bos = new BufferedOutputStream(response.getOutputStream());
          byte[] buff = new byte[2048];
          int bytesRead;
          while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
              bos.write(buff,0,bytesRead);
          }
      } catch(final IOException e) {
          System.out.println ( "出现IOException." + e );
      } finally {
          if (bis != null)
     try {
      bis.close();
     } catch (IOException e) {
      e.printStackTrace();
     }
          if (bos != null)
     try {
      bos.close();
     } catch (IOException e) {
      e.printStackTrace();
     }
      }

 

 

 

 

你可能感兴趣的:(servlet)