| | |
| | | } |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * 下载文件 |
| | | * @param response 响应对象 |
| | | * @param fileObjectBO 文件的信息,包含文件的输入流 |
| | | * @param closeInputStream 是否关闭流 |
| | | * @throws IOException 下载出错的时候抛出异常 |
| | | */ |
| | | public static void downloadFileLocal(HttpServletResponse response, FileObjectBO fileObjectBO,boolean closeInputStream) throws IOException { |
| | | MediaType mediaType = MediaTypeFactory.getMediaType(fileObjectBO.getFileExtension()).orElse(MediaType.APPLICATION_OCTET_STREAM); |
| | | // 设置强制下载不打开 |
| | | response.setContentType(mediaType.toString()+";application/force-download;charset=UTF-8"); |
| | | try{ |
| | | String fileName = URLEncoder.encode(fileObjectBO.getName(), "UTF8"); |
| | | response.addHeader("Content-Disposition", "attachment;filename="+ fileName+ ";filename*=utf-8''"); |
| | | }catch(Exception e){ |
| | | if(log.isErrorEnabled()){ |
| | | log.error("设置文件的名称到响应流的时候出错",e); |
| | | } |
| | | } |
| | | response.setCharacterEncoding("UTF-8"); |
| | | Cookie cookie = new Cookie("fileDownload", "true"); |
| | | cookie.setPath("/"); |
| | | response.addCookie(cookie); |
| | | if(closeInputStream) { |
| | | try (InputStream ins = (fileObjectBO.getInputStream() != null ? fileObjectBO.getInputStream() : new FileInputStream(fileObjectBO.getFileLocalPath()))) { |
| | | IOUtils.copy(ins, response.getOutputStream()); |
| | | } catch (IOException e) { |
| | | //有可能客户端的链接 |
| | | if (log.isErrorEnabled()) { |
| | | log.error("写入文件到响应流出错", e); |
| | | } |
| | | throw e; |
| | | } |
| | | }else{ |
| | | try { |
| | | InputStream ins = (fileObjectBO.getInputStream() != null ? fileObjectBO.getInputStream() : new FileInputStream(fileObjectBO.getFileLocalPath())); |
| | | IOUtils.copy(ins, response.getOutputStream()); |
| | | } catch (IOException e) { |
| | | //有可能客户端的链接 |
| | | if (log.isErrorEnabled()) { |
| | | log.error("写入文件到响应流出错", e); |
| | | } |
| | | throw e; |
| | | } |
| | | } |
| | | } |
| | | |
| | | } |