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;
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_25927437/article/details/80856734