HttpServletResponse 前端响应压缩文件And在压缩包中新建文件夹


(1)---pox配置
   < dependency >
              < groupId > org.apache.commons </ groupId >
              < artifactId > commons-compress </ artifactId >
              < version > 1.9 </ version >

   </dependency>

 (2)---建立公共方法

/**
 *Zip文件工具类
 *
 * @author   @author wenfei.fang
 */
public class ZipFileUtil {
     
      /**
      *通过 try-with-resources 的语法来创建流,可以安全的自动关闭
      *  @author wenfei.fang
      * @param ZipArchiveOutputStream  压缩的文件流
      * @param sonFileName      向压缩文件插入的文件名 test.txt
      * @param inStreamFile      test.txt文件输入流
      * @throws IOException     Io异常
      */
      public static void compressFilesZip(ZipArchiveOutputStream  zaos , String  SonFileName , InputStream  inStreamFile ) {
           if ( SonFileName != null && SonFileName .length() > 0) {
                    try {
                         zaos .setUseZip64(Zip64Mode. AsNeeded );
                        ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry( SonFileName );
                         zaos .putArchiveEntry( zipArchiveEntry );
                         try {
                              byte [] buffer = new byte [1024 * 5];
                              int len = -1;
                              while (( len = inStreamFile .read( buffer )) != -1) {
                                   zaos .write( buffer , 0, len );
                             }
                              zaos .closeArchiveEntry();
                        } catch (Exception e ) {
                              throw new RuntimeException( e );
                        } finally {
                              if ( inStreamFile != null )
                                   inStreamFile .close();
                        }
                         zaos .finish();
                   } catch (Exception e ) {
                         throw new RuntimeException( e );
                   } finally {
                         try {
                              if ( inStreamFile != null ) {
                                   inStreamFile .close();
                             }
                        } catch (IOException e ) {
                              throw new RuntimeException( e );
                        }
                   }

              }

          

     }
     
      /**
      *  @author wenfei.fang
      * @param zipOutputStream  压缩的文件流
      * @param sonFileName      向压缩文件插入的文件名 test.txt
      * @param inStreamFile      test.txt文件输入流
      * @throws IOException     Io异常
      */
      public static  void  writeFile(ZipOutputStream zipOutputStream , String sonFileName , InputStream inStreamFile ) throws IOException {
            ZipEntry  ze = new ZipEntry( sonFileName );
             zipOutputStream .putNextEntry( ze );
             byte [] buffer = new byte [1204];
             int len = -1;
            while (( len = inStreamFile .read( buffer )) != -1) {
            System. err .println( len );
             zipOutputStream .write( buffer , 0, len );
            }
            inStreamFile .close();
      }

     
      /**
      * @author wenfei.fang
      * @用apache commentsio包中的IOUtils中的方法
      * @param zipOutputStream  压缩的文件流
      * @param sonFileName      向压缩文件插入的文件名 test.txt
      * @param inStreamFile      test.txt文件输入流
      * @throws IOException     Io异常
      * @message Copy bytes from a large (over 2GB) InputStream to an OutputStream. 将字节超过2G的字节输入流复制到输出流中
      *  //IOUtils.copyLarge(input, output)
      */
      public static void writeFileUseIOUtils(ZipOutputStream zipOutputStream , String sonFileName , InputStream inStreamFile ) throws IOException {
            ZipEntry ze = new ZipEntry( sonFileName );
            zipOutputStream .putNextEntry( ze );
            IOUtils.copy( inStreamFile , zipOutputStream );
            IOUtils.closeQuietly( inStreamFile );
      }

}



在control层的操作     

@RequestMapping (value = "/api/fblMaster/downloadNet23" )
      public @ResponseBody String downloadNet2(HttpServletResponse  response ) throws MalformedURLException {
             //通过给定的URL字符串创建URL
             URL url = new URL( "http://10.152.244.25:16200/cs/idcplg?IdcService=GET_FILE&dID=23378&dDocName=GGSTEST16200022613&allowInterrupt=1" );
             try {
                     URLConnection conn = url .openConnection();
                    InputStream inStreamFile = conn .getInputStream();
                   
                    URLConnection conn1 = url .openConnection();
                    InputStream inStreamFile1 = conn1 .getInputStream(); 
                   
                    URLConnection conn2 = url .openConnection();
                    InputStream inStreamFile2 = conn2 .getInputStream(); 
                   
                    URLConnection conn21 = url .openConnection();
                    InputStream inStreamFile21 = conn21 .getInputStream(); 
                 
                   response .setHeader( "Content-Disposition" , "attachment; filename=Barcode_Label_Approval_Verification" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".zip" );
                     response .setCharacterEncoding( "UTF-8" );
                     response .setContentType( "application/x-msdownload" );

                   OutputStream  out = response .getOutputStream();
                   ZipOutputStream  zos = new ZipOutputStream( out );   
          
          ZipFileUtil.writeFileUseIOUtils( zos , "test1.jpg" , inStreamFile );
                   ZipFileUtil.writeFileUseIOUtils( zos , "sonFileName1/test1.jpg" , inStreamFile1 );
                   ZipFileUtil.writeFileUseIOUtils( zos , "sonFileName2/test2.jpg" , inStreamFile2 );
                   ZipFileUtil.writeFileUseIOUtils( zos , "sonFileName2/test1.jpg" , inStreamFile21 );
             //关闭文件流(如果不关闭可能在压缩包中的文件只有名称没有文件内容)    
           IOUtils.closeQuietly( zos );
             } catch (FileNotFoundException e ) {
                 e .printStackTrace();
             } catch (IOException e ) {
                 e .printStackTrace();
             }
             return null ;
         }


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用以下代码将字节数组写入到HTTP响应,以实现下载压缩文件的功能: ```java import java.io.IOException; import java.util.zip.ZipOutputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class DownloadServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置响应内容类型为zip文件 response.setContentType("application/zip"); // 设置响应头,指定文件名 response.setHeader("Content-Disposition", "attachment; filename=\"compressed.zip\""); // 获取要压缩的字节数组 byte[] data = getCompressedData(); // 将字节数组写入HTTP响应 response.getOutputStream().write(data); } private byte[] getCompressedData() { // 这里是你获取压缩字节数组的逻辑,可以是从文件读取或通过其他方式生成 // 假设这里直接返回一个示例字节数组 return new byte[] { 0x50, 0x4B, 0x03, 0x04, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ... }; } } ``` 上述代码,我们创建了一个 `DownloadServlet` 类来处理 HTTP GET 请求。在 `doGet` 方法,我们首先设置响应的内容类型为 zip 文件,然后设置响应头,指定文件名为 "compressed.zip"。接下来,我们调用 `getCompressedData` 方法获取要压缩的字节数组,并将其写入到 HTTP 响应的输出流,实现下载压缩文件的功能。 请注意,以上代码只是一个示例,你需要根据实际情况进行适当的修改和处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值