OSS文件打包下载

OSS文件打包下载:

直接上代码如下:

/**
     * 测试-批量打包下载
     * @param ossFileKeyPaths  对应文件的 key 和 name
     * @param zipFileName 整个包的名称
     * @param response
     */
    @Override
    public void batchDownLoadOssFile(Map<String,String> ossFileKeyPaths, String zipFileName, HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/zip; charset=utf-8");
        //要下载成什么类型的文件,这里直接加后缀
        response.setHeader("Content-Disposition", "attachment;fileName=" + zipFileName + ".zip");
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        BufferedInputStream bis = null;
        try {
            ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
            Set<String> ossKeyPathSet = ossFileKeyPaths.keySet();
            for (String ossKeyPath:ossKeyPathSet) {
                // 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
                /*Date expiration = new Date(new Date().getTime() + 3600 * 1000);
                URL signedUrl = ossClient.generatePresignedUrl(bucketName, ossFileKeyPath, expiration);*/
                // 使用签名URL发送请求。
                String ossFileKey = this.createOssKey(OssTokenConstants.FILE_ATTACHMENT.getOssToken(), ossKeyPath);
                OSSObject ossObject = ossClient.getObject(new GetObjectRequest(bucketName, ossFileKey));
                if (ossObject != null) {
                    ZipEntry zipEntry = new ZipEntry(ossFileKeyPaths.get(ossKeyPath));
                    InputStream inputStream = ossObject.getObjectContent();
                    byte[] buffs = new byte[1024 * 10];
                    zos.putNextEntry(zipEntry);
                    bis = new BufferedInputStream(inputStream, 1024 * 10);
                    int read;
                    while ((read = bis.read(buffs, 0, 1024 * 10)) != -1) {
                        zos.write(buffs, 0, read);
                    }
                    ossObject.close();
                }
            }
            zos.close();
            //关闭流
        } catch (Exception e) {
            logger.error("打包下载发生异常:",e);
        } finally {
            try {
                if (null != bis) {
                    bis.close();
                }
                response.getOutputStream().flush();
                response.getOutputStream().close();
                ossClient.shutdown();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


//根据ossFileKeyPath生成对应的Key(可忽略不用)
private String createOssKey(String ossToken,String ossFileKeyPath){
        String ossFileKey =  this.createOssTokenFileKeyPrefix(ossToken) + ( ossFileKeyPath.indexOf("/")==0?ossFileKeyPath:"/"+ossFileKeyPath);
        return ossFileKey;
    }

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章