下載文件

下載文件

public void downLoad(String filePath){  
            HttpServletResponse response = this.getResponse();

            BufferedInputStream bis=null;
            BufferedOutputStream  bos=null;
            try{
                 String filename=filePath.substring(filePath.lastIndexOf("/") + 1, filePath.length());
                 response.setContentType(returnFileType(filename.substring(filename.lastIndexOf(".")).toUpperCase()));
                 response.setCharacterEncoding("gbk");
                 response.setHeader("Content-Disposition","filename="+new String(filename.getBytes("gbk"),"iso8859-1"));
                 bis =new BufferedInputStream(new FileInputStream(filePath));
                 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(Exception e){
                 e.printStackTrace();
            }finally {
             if (bis != null)
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
             if (bos != null)
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    Tip:
    ContentType設置如下:    
public static String returnFileType(String extName){

             if(".DOC" .equals(extName)){return "application/msword";}
             else if(".DOCX" .equals(extName)){return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";}
             else if(".PDF" .equals(extName)){return "application/pdf";}
             else if(".TXT" .equals(extName)){return "text/html";}
             else if(".XLS" .equals(extName)){return "application/vnd.ms-excel";}
             else if(".XLSX" .equals(extName)){return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";}
             else if(".PPT" .equals(extName)){return "application/vnd.ms-powerpoint";}
             else if(".PPTX" .equals(extName)){return "application/vnd.openxmlformats-officedocument.presentationml.presentation";}
             else if(".BMP" .equals(extName)){return "image/bmp";}
             else if(".GIF" .equals(extName)){return "image/gif";}
             else if(".IEF" .equals(extName)){return "image/ief";}
             else if(".JPEG" .equals(extName)){return "image/jpeg";}
             else if(".JPG" .equals(extName)){return "image/jpeg";}
             else if(".PNG" .equals(extName)){return "image/png";}
             else if(".TIFF" .equals(extName)){return "image/tiff";}
             else if(".TIF" .equals(extName)){return "image/tif";}
             return "";
        }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章