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

 

 

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