1. 程式人生 > >JAVA檔案下載程式碼(相容safari的亂碼問題)

JAVA檔案下載程式碼(相容safari的亂碼問題)


public void downFile(HttpServletResponse response, HttpServletRequest httpServletRequest) {
        response.setContentType("application/octet-stream");

        String path = httpServletRequest.getParameter("file");
        String fileName=path.substring(path.lastIndexOf("/")+1);
        try {
            //bugfix: fileName包含中文導致fileNotFound
            path = path.substring(0,path.lastIndexOf("/")+1) + URLEncoder.encode(fileName, "UTF-8");

            String userAgent = httpServletRequest.getHeader("User-Agent").toLowerCase();
            //chrome頭也包含safari,需要排除chrome
            if(userAgent.contains("safari") && !userAgent.contains("chrome")){
                //處理safari的亂碼問題
                byte[] bytesName = fileName.getBytes("UTF-8");
                fileName = new String(bytesName, "ISO-8859-1");
                response.setHeader("content-disposition", "attachment;fileName="+ fileName);
            }else{
                response.setHeader("content-disposition", "attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));
            }
//            //檔名外的雙引號處理firefox的空格截斷問題
//            response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));

            OutputStream output = response.getOutputStream();
            URL url = new URL(path);
            //輸入緩衝流
            BufferedInputStream bis=new BufferedInputStream(url.openStream());
            //輸出緩衝流
            BufferedOutputStream bos=new BufferedOutputStream(output);
            //緩衝位元組數
            byte[] data =new byte[4096];
            int size=0;
            size=bis.read(data);
            while (size!=-1){
                bos.write(data,0,size);
                size=bis.read(data);
            }
            bis.close();
            bos.flush();//清空輸出緩衝流
            bos.close();
        } catch (Exception e) {
            logger.error("downFile error",e);
        }
    }