1. 程式人生 > >java 檔案下載後中文名亂碼以及特殊字元被轉義的問題

java 檔案下載後中文名亂碼以及特殊字元被轉義的問題

    @SuppressWarnings({ "deprecation"})
    public ResponseEntity<byte[]> downLoadFile(HttpServletRequest request,String fileId,String basePath){
        InputStream in= null;
        ByteArrayOutputStream daos = null;
        try {
            in = getInputStreamByFileId(in, fileId, basePath);
            daos = new ByteArrayOutputStream();
            if (in != null && daos != null) {
                //獲取檔案儲存資訊
                BaseFileService baseFileService = (BaseFileService) ComponentFactory.getBean("baseFileService");
                BaseFile baseFile = baseFileService.getBaseFileByFileId(fileId);
                String fileName = baseFile.getFileName();
                //解決檔名亂碼的問題
                fileName = decodingFileName(fileName, "gbk");
                
                byte[] buff = new byte[1024 * 1024];
                int len = 0;
                while ((len = in.read(buff, 0, buff.length)) != -1) {
                    daos.write(buff, 0, len);
                }
                daos.flush();
                // 頭資訊
                HttpHeaders headers = new HttpHeaders();
                headers.setContentDispositionFormData("attachment", fileName);
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                return new ResponseEntity<byte[]>(daos.toByteArray(), headers, HttpStatus.OK);
            }else {
                return null;
            }
        } catch (IOException e) {
            throw new ServiceException("檔案下載失敗!");
        } catch (Exception e) {
            throw new ServiceException("下載檔案失敗:"+e.getMessage());
        } finally{
            try {
                if(in != null){
                    in.close();
                }
                if(daos != null){
                    daos.close();
                }
            }catch (IOException e) {
                throw new ServiceException("關閉流物件出錯");
            }
        }
    }

/**

     * @Title: decodingFileName
     * @Description: 檔名稱進行編碼
     * @param fileName
     * @param encoding
     * @return
     */
    private static String decodingFileName(String fileName,String encoding){
        try {
            return new String(fileName.getBytes(encoding), "iso8859-1");
        } catch (UnsupportedEncodingException e) {
            return fileName;
        }
    }