压缩包工具类(下载)
import com. enlistboot. common. core. FileResult ;
import org. springframework. http. HttpHeaders ;
import org. springframework. util. ObjectUtils ; import javax. servlet. http. HttpServletResponse ;
import java. io. * ;
import java. net. HttpURLConnection ;
import java. net. URL ;
import java. net. URLEncoder ;
import java. util. * ;
import java. util. zip. ZipEntry ;
import java. util. zip. ZipOutputStream ; public class ZipUtil { public static void downloadZip ( HttpServletResponse response, String fileName, List < FileResult > list) { try { BufferedInputStream bis = null ; java. io. File file = null ; ByteArrayOutputStream output = new ByteArrayOutputStream ( ) ; ZipOutputStream zipOut = new ZipOutputStream ( response. getOutputStream ( ) ) ; InputStream fis = null ; response. setCharacterEncoding ( "UTF-8" ) ; response. setContentType ( "application/octet-stream;charset=UTF-8" ) ; response. setHeader ( Content - Disposition , "attachment;filename=\"" + URLEncoder . encode ( fileName + ".zip" , "UTF-8" ) + "\"" ) ; Map < String , String > map = new HashMap < > ( ) ; for ( FileResult studentInfoVo : list) {
if ( ObjectUtils . isEmpty ( map. get ( studentInfoVo. getFolderName ( ) ) ) ) { String path = studentInfoVo. getUrl ( ) ;
URL url = new URL ( path) ; HttpURLConnection connection = ( HttpURLConnection ) url. openConnection ( ) ; connection. setConnectTimeout ( 5000 ) ; connection. setReadTimeout ( 5000 ) ; fis = connection. getInputStream ( ) ; if ( ObjectUtils . isEmpty ( map. get ( studentInfoVo. getFolderName ( ) ) ) ) { zipOut. putNextEntry ( new ZipEntry ( fileName + "/" + studentInfoVo. getFolderName ( ) ) ) ; } bis = new BufferedInputStream ( fis) ; byte [ ] buffer = new byte [ 1024 ] ; int len = - 1 ; while ( ( len = bis. read ( buffer) ) != - 1 ) { output. reset ( ) ; output. write ( buffer, 0 , len) ; zipOut. write ( output. toByteArray ( ) ) ; } map. put ( studentInfoVo. getFolderName ( ) , studentInfoVo. getFolderName ( ) ) ; zipOut. flush ( ) ; zipOut. closeEntry ( ) ; bis. close ( ) ; output. close ( ) ; } } fis. close ( ) ; zipOut. close ( ) ; } catch ( Exception e) { e. printStackTrace ( ) ; } }
}