JAVA文件下载

来源:互联网 发布:怎么注册免费域名 编辑:程序博客网 时间:2024/05/16 14:33
    //文件下载
    public static String downloadFile(File file) {
            HttpServletResponse response = ServletActionContext.getResponse();
            FileInputStream fis = null;
            BufferedInputStream buff = null;
            OutputStream out = null;
            try {
               /* 如果文件存在 */
               if (file.exists()) {
                   //设置为没有缓存
                   response.reset();
                   //设置response的编码方式
                   //response.setContentType("application/x-download");  
                   response.setContentType("application/ms-excel"); //这一句更细化,告诉浏览器要下载的是excel文件
                   //设置下载文件名
                   response.setHeader("Content-Disposition", "filename="+new String(file.getName().getBytes(),"UTF-8"));
                   //读出文件到i/o流
                   fis=new FileInputStream(file);
                   buff=new BufferedInputStream(fis);
                   //从response对象中得到输出流,准备下载
                   out = response.getOutputStream();
                   //PrintWriter out = response.getWriter();随便哪句都可以
                   //以字节的方式写入内容
                   int i;   
                   while((i = buff.read()) != -1){     
                       out.write(i);
                   }
                   //把内容全部推到文档里
                   out.flush();   
               }else{
                   return "download fail";//文件不存在
               }
           } catch (Exception e) {
            // TODO: handle exception
           }finally{
               try {
                   if (buff != null)  
                       buff.close();      
                   if (out != null)  
                       out.close();     
               } catch (IOException e) {
                   return "download fail";
               }
           }
        return "download success";
    }
0 0