OSSUtil.java 30.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
package cn.timer.api.utils.aliyun;

import java.io.*;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import cn.timer.api.config.sftp.SftpConfiguration;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jcraft.jsch.ChannelSftp;
import io.swagger.models.auth.In;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.bouncycastle.jce.exception.ExtIOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.event.ProgressEvent;
import com.aliyun.oss.event.ProgressEventType;
import com.aliyun.oss.event.ProgressListener;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.timer.api.utils.Result;
import cn.timer.api.utils.ResultUtil;

import javax.servlet.http.HttpServletResponse;

/**
 * OSS接口操作示例 1.创建空间 2.上传文件 3.下载文件
 *
 * @author dsc
 */
@Component
public class OSSUtil {

    @Value("${config-8timer.Aliyun.endpoint}")
    private String endpoint;

    @Value("${config-8timer.Aliyun.ACCESSKEY_ID}")
    private String accessKeyId;

    @Value("${config-8timer.Aliyun.SECRET}")
    private String accessKeySecret;

    @Value("${config-8timer.Aliyun.bucketName}")
    private String bucketName;

    @Value("${config-8timer.Aliyun.bucketName_pri}")
    private String bucketName_pri;

    @Value("${config-8timer.Aliyun.project_package}")
    private String project_package;

    @Value("${config-8timer.Aliyun.expirationTime}")
    private String expirationTime;

    @Value("${config-8timer.Aliyun.expirationTime_pri}")
    private String expirationTime_pri;

    @Value("${zip.path}")
    private String zipPath;


    @Autowired
    private SftpConfiguration config;


    /**
     * 1.创建储存空间 sout控制台輸出 储存空间名
     *
     * @param bucketName OSS空间名
     * @return 成功信息
     */
    public Result<Void> createZone(String bucketName) {
        // Endpoint以杭州为例,其它Region请按实际情况填写。
        // 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录
        // https://ram.console.aliyun.com 创建RAM账号。
        // 创建OSSClient实例。

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 创建存储空间。
        ossClient.createBucket(bucketName);
        // 关闭OSSClient。
        ossClient.shutdown();
        // 控制台输出空间名
        Logoutput("bucketName:" + bucketName);
        // 返回成功
        return ResultUtil.success("创建OSS空间成功");
    }

    /**
     * 2.上传文件到8time-v2
     *
     * @param path 上传路径(用'/'分包)
     * @param ins  输入流
     * @return
     */
    public String uploadFile(File path, InputStream ins) {
        // <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg。
        // String objectName = "8time-v2/test/123.jpg";
        // 创建OSSClient实例。
        Logoutput(endpoint);
        Logoutput(accessKeyId);
        Logoutput(accessKeySecret);
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 创建PutObjectRequest对象。
        // 项目名+用户公司id+模块名+文件夹名+文件名
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, path.getPath(), ins);
        // [file1,file2,file3],["mk1/img","mk1"]
        // 如果需要上传时设置存储类型与访问权限,请参考以下示例代码。
        // ObjectMetadata metadata = new ObjectMetadata();
        // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS,
        // StorageClass.Standard.toString());
        // metadata.setObjectAcl(CannedAccessControlList.Private);
        // putObjectRequest.setMetadata(metadata);

        // 上传文件。
        ossClient.putObject(putObjectRequest);

        // 设置URL过期时间为100年。 1s 1h 1d 1y 100y
//		Date expiration = new Date(new Date().getTime() + 1000L * 3600 * 24 * 365 * 100);
        Date now = new Date();
        Date expiration = DateUtil.offset(now, DateField.YEAR, 100); // 一百年之后过期
        // 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
        URL url = ossClient.generatePresignedUrl(bucketName, path.getPath(), expiration);
        Logoutput(String.valueOf(url));

        // 关闭OSSClient。
        ossClient.shutdown();
        // 返回上传成功的文件名
        return url.toString().substring(0, url.toString().lastIndexOf("?"));
    }

    /**
     * 3.上传文件到8time-v2-private
     *
     * @param path 上传路径(用'/'分包)
     * @param ins  输入流
     * @return 文件路径
     */
    public String uploadPrivateFile(String path, InputStream ins) {
        // <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg。
        // String objectName = "8time-v2/test/123.jpg";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 创建PutObjectRequest对象。
        // 项目名+用户公司id+模块名+文件夹名+文件名
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName_pri, path, ins);
        // [file1,file2,file3],["mk1/img","mk1"]
        // 如果需要上传时设置存储类型与访问权限,请参考以下示例代码。
        // ObjectMetadata metadata = new ObjectMetadata();
        // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS,
        // StorageClass.Standard.toString());
        // metadata.setObjectAcl(CannedAccessControlList.Private);
        // putObjectRequest.setMetadata(metadata);

        // 上传文件。
        ossClient.putObject(putObjectRequest);

        // 设置URL过期时间为10分钟
        Date expiration = new Date(new Date().getTime() + 1000 * 600);
        // 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
        URL url = ossClient.generatePresignedUrl(bucketName_pri, path, expiration);
        Logoutput(String.valueOf(url));

        // 关闭OSSClient。
        ossClient.shutdown();
        // 返回上传成功的文件名
        return path;
    }

    /**
     * 4.从OSS下载文件
     *
     * @param path     本地储存文件路径
     * @param orgCode  公司id
     * @param dir      包名
     * @param fileName 文件名
     * @param moudle   模块名
     * @return 完整文件名
     */
    public Result<String> downloadFile(String orgCode, String moudle, String dir, String fileName, String path) {
        // <yourObjectName>从OSS下载文件时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg。
        // String objectName = "8time-v2/test/123.jpg";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。
        ossClient.getObject(
                new GetObjectRequest(bucketName, project_package + orgCode + "/" + moudle + "/" + dir + "/" + fileName),
                new File(path + fileName));

        // 关闭OSSClient。
        ossClient.shutdown();
        // 完整路径的文件名
        Logoutput("objectName:" + project_package + orgCode + "/" + moudle + "/" + dir + "/" + fileName);
        Logoutput("path:" + path + fileName);
        // 返回成功的本地路径
        return ResultUtil.success(path + fileName);
    }

    public Result<BufferedReader> downloadFile(String objectName) throws IOException {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
        OSSObject ossObject = ossClient.getObject(bucketName, objectName);

        // 读取文件内容。
        System.out.println("Object content:");
        BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));
        while (true) {
            String line = reader.readLine();
            if (line == null)
                break;

            System.out.println("\n" + line);
        }
        // 数据读取完成后,获取的流必须关闭,否则会造成连接泄漏,导致请求无连接可用,程序无法正常工作。
        reader.close();

        // 关闭OSSClient。
        ossClient.shutdown();
        return ResultUtil.data(reader, "下载成功");
    }

    public InputStream downloadFileInputStream(String objectName) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
        OSSObject ossObject = ossClient.getObject(bucketName, objectName);

        // 关闭OSSClient。
        //ossClient.shutdown();
        return ossObject.getObjectContent();
    }

    /**
     * 文件输入流批量上传
     *
     * @param request 获取参数
     * @param files   批量文件
     * @return 返回上传成功或失败的信息
     */
    public String uploadFile(MultipartHttpServletRequest request, List<MultipartFile> files) {

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        String newFileName = null;
        URL url = null;
        try {
            // 上传文件
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                    request.getSession().getServletContext());
            // 判断 request 是否有文件上传,即多部分请求
            if (multipartResolver.isMultipart(request)) {
                // 转换成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                // 取得request中的所有文件名
                Iterator<String> iter = multiRequest.getFileNames();
                // 此处上传单个文件,如需多个文件改为while循环
                while (iter.hasNext()) {

                    // 取得上传文件
                    files = multiRequest.getFiles(iter.next());
                    if (files != null) {
                        // 取得当前上传文件的文件名称
                        String myFileName = null;

                        for (MultipartFile file : files) {
                            myFileName = file.getOriginalFilename();

                            // 如果名称不为“”,说明该文件存在,否则说明该文件不存在
                            if (StrUtil.isNotEmpty(myFileName.trim())) {
                                newFileName = System.currentTimeMillis()
                                        + myFileName.substring(myFileName.lastIndexOf("."));
                                // 上传客户端文件到oss,如直接上传服务器文件到oss,可使用new FileInputStream( new File("服务器文件路径"))
                                ossClient.putObject(bucketName, newFileName, file.getInputStream());
                                // 设置URL过期时间为100年。 1s 1h 1d 1y 100y
                                Date expiration = new Date(new Date().getTime() + Long.parseLong(expirationTime));
                                // 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
                                url = ossClient.generatePresignedUrl(bucketName, newFileName, expiration);
                                Logoutput(String.valueOf(url));
                            }

                        }

                    }
                }
            }
        } catch (IOException e) {
            e.getStackTrace();
        } finally {
            // 关闭ossClient
            if (null != ossClient)
                ossClient.shutdown();
        }
        return url.toString();

        /*
         * if (file == null || file.getSize() <= 0) { return
         * ResultUtil.error("上传的文件为空,请重新选择!"); } else { try {
         * OSSUtil.uploadFile(userBean.getOrgCode(), className,
         * file.getOriginalFilename(), file.getInputStream()); } catch (IOException e) {
         * e.printStackTrace(); } return ResultUtil.success("上传成功"); }
         */
    }

    /**
     * 获取8time-v2文件的url
     *
     * @return url地址
     */
    public String getUrl(String path) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 设置URL过期时间为100年。 1s 1h 1d 1y 10y
        Date expiration = new Date(new Date().getTime() + Long.parseLong(expirationTime));
        // 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
        URL url = ossClient.generatePresignedUrl(bucketName, path, expiration);
        Logoutput(String.valueOf(url));
        // 关闭OSSClient。
        ossClient.shutdown();
        return url.toString();
    }

    /**
     * 获取8time-v2-private文件的url
     *
     * @return url地址
     */
    public String getUrlP(String path) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 设置URL过期时间为10分钟。
        Date expiration = new Date(new Date().getTime() + Long.parseLong(expirationTime_pri));
        // 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
        URL url = ossClient.generatePresignedUrl(bucketName, path, expiration);
        Logoutput(String.valueOf(url));
        // 关闭OSSClient。
        ossClient.shutdown();
        return url.toString();
    }

    /**
     * 删除单个
     *
     * @param objectName 文件名
     */
    public void delSingleFile(String objectName) {
//		// Endpoint以杭州为例,其它Region请按实际情况填写。
//		String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
//		// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
//		String accessKeyId = "<yourAccessKeyId>";
//		String accessKeySecret = "<yourAccessKeySecret>";
//		String bucketName = "<yourBucketName>";
//		String objectName = "<yourObjectName>";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 删除文件。如需删除文件夹,请将ObjectName设置为对应的文件夹名称。如果文件夹非空,则需要将文件夹下的所有object删除后才能删除该文件夹。
        ossClient.deleteObject(bucketName, objectName);

        // 关闭OSSClient。
        ossClient.shutdown();
    }

    /**
     * 删除多个文件
     *
     * @param keys  需要删除的文件。
     * @param quiet 返回模式。true表示简单模式,false表示详细模式。默认为详细模式。
     * @return 删除结果。详细模式下为删除成功的文件列表,简单模式下为删除失败的文件列表。
     */
    public List<String> delFiles(List<String> keys, boolean quiet) {
//		// Endpoint以杭州为例,其它Region请按实际情况填写。
//		String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
//		// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
//		String accessKeyId = "<yourAccessKeyId>";
//		String accessKeySecret = "<yourAccessKeySecret>";
//		String bucketName = "<yourBucketName>";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 删除文件。key等同于ObjectName,表示删除OSS文件时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg。
//		List<String> keys = new ArrayList<String>();
//		keys.add("key0");
//		keys.add("key1");
//		keys.add("key2");

        DeleteObjectsResult deleteObjectsResult = ossClient
                .deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(keys).withQuiet(quiet));
        List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();

        // 关闭OSSClient。
        ossClient.shutdown();

        return deletedObjects;
    }

    /**
     * 删除指定前缀(prefix)的文件
     *
     * @param prefix
     */
    public void delPrefixWith(String prefix) {
//		// Endpoint以杭州为例,其它Region请按实际情况填写。
//		String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
//		// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录
//		// https://ram.console.aliyun.com 创建RAM账号。
//		String accessKeyId = "<yourAccessKeyId>";
//		String accessKeySecret = "<yourAccessKeySecret>";
//		String bucketName = "<yourBucketName>";
//
//		// 指定前缀。
//		final String prefix = "<yourkeyPrefix>";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 列举所有包含指定前缀的文件并删除。
        String nextMarker = null;
        ObjectListing objectListing = null;
        do {
            ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName).withPrefix(prefix)
                    .withMarker(nextMarker);

            objectListing = ossClient.listObjects(listObjectsRequest);
            if (objectListing.getObjectSummaries().size() > 0) {
                List<String> keys = new ArrayList<String>();
                for (OSSObjectSummary s : objectListing.getObjectSummaries()) {
                    Logoutput("key name: " + s.getKey());
                    keys.add(s.getKey());
                }
                DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucketName).withKeys(keys);
                ossClient.deleteObjects(deleteObjectsRequest);
            }

            nextMarker = objectListing.getNextMarker();
        } while (objectListing.isTruncated());

        // 关闭OSSClient。
        ossClient.shutdown();
    }

    /*
     * (跨域资源) // Endpoint以杭州为例,其它Region请按实际情况填写。 String endpoint =
     * "http://oss-cn-hangzhou.aliyuncs.com"; //
     * 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录
     * https://ram.console.aliyun.com 创建RAM账号 String accessKeyId =
     * "<yourAccessKeyId>"; String accessKeySecret = "<yourAccessKeySecret>"; String
     * bucketName = "<yourBucketName>";
     *
     * // 创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(endpoint,
     * accessKeyId, accessKeySecret);
     *
     * SetBucketCORSRequest request = new SetBucketCORSRequest(bucketName);
     *
     * // 跨域资源共享规则的容器,每个存储空间最多允许10条规则。 ArrayList<CORSRule> putCorsRules = new
     * ArrayList<CORSRule>();
     *
     * CORSRule corRule = new CORSRule();
     *
     * ArrayList<String> allowedOrigin = new ArrayList<String>(); // 指定允许跨域请求的来源。
     * allowedOrigin.add( "http://www.b.com");
     *
     * ArrayList<String> allowedMethod = new ArrayList<String>(); //
     * 指定允许的跨域请求方法(GET/PUT/DELETE/POST/HEAD)。 allowedMethod.add("GET");
     *
     * ArrayList<String> allowedHeader = new ArrayList<String>(); //
     * 是否允许预取指令(OPTIONS)中Access-Control-Request-Headers头中指定的Header。
     * allowedHeader.add("x-oss-test");
     *
     * ArrayList<String> exposedHeader = new ArrayList<String>(); //
     * 指定允许用户从应用程序中访问的响应头。 exposedHeader.add("x-oss-test1"); //
     * AllowedOrigins和AllowedMethods最多支持一个星号(*)通配符。星号(*)表示允许所有的域来源或者操作。
     * corRule.setAllowedMethods(allowedMethod);
     * corRule.setAllowedOrigins(allowedOrigin); //
     * AllowedHeaders和ExposeHeaders不支持通配符。 corRule.setAllowedHeaders(allowedHeader);
     * corRule.setExposeHeaders(exposedHeader); //
     * 指定浏览器对特定资源的预取(OPTIONS)请求返回结果的缓存时间,单位为秒。 corRule.setMaxAgeSeconds(10);
     *
     * // 最多允许10条规则。 putCorsRules.add(corRule); // 已存在的规则将被覆盖。
     * request.setCorsRules(putCorsRules); ossClient.setBucketCORS(request);
     *
     * // 关闭OSSClient。 ossClient.shutdown();
     */

    public void download(String url, String savePath) {
        // Endpoint以杭州为例,其它Region请按实际情况填写。
//		String endpoint = "http://oss-cn-shenzhen.aliyuncs.com";
//		// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录
//		// https://ram.console.aliyun.com 创建RAM账号。
//		String accessKeyId = "LTAI4FuaShJWQ1dggsFWG5CC";
//		String accessKeySecret = "EJ6qToT4T4u0B5Rb6qrta9WkyGHvGR";
//		String bucketName = "8time-v2";
//		String objectName = "8timer2.0/117/test/测试.pdf";

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//				String url = "http://8time-v2.oss-cn-shenzhen.aliyuncs.com/8timer2.0/310/qyxx/filepath/158872957193802f4a85a-9dd9-483a-9049-86fac5c73bd5.pdf?Expires=4747952308&OSSAccessKeyId=LTAI4FuaShJWQ1dggsFWG5CC&Signature=z%2FNIX0RrxnLuBLAS9olPpxxsCrI%3D";
        try {
            // 带进度条的下载。
            ObjectMetadata a = ossClient.getObject(new GetObjectRequest(new URL(url), null), new File(savePath));
            System.err.println(a);
//					new File("C:\\Users\\Lenovo\\Desktop\\8小时\\test2.pdf"));
//					// 带进度条的下载。
//					ossClient.getObject(new GetObjectRequest(bucketName, objectName).<GetObjectRequest>withProgressListener(
//							new GetObjectProgressListener()), new File("C:\\Users\\Lenovo\\Desktop\\8小时\\test.pdf"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 关闭OSSClient。
        ossClient.shutdown();
    }

    static class GetObjectProgressListener implements ProgressListener {
        private long bytesRead = 0;
        private long totalBytes = -1;
        private boolean succeed = false;

        @Override
        public void progressChanged(ProgressEvent progressEvent) {
            long bytes = progressEvent.getBytes();
            ProgressEventType eventType = progressEvent.getEventType();
            switch (eventType) {
                case TRANSFER_STARTED_EVENT:
                    System.out.println("Start to download......");
                    break;
                case RESPONSE_CONTENT_LENGTH_EVENT:
                    this.totalBytes = bytes;
                    System.out.println(this.totalBytes + " bytes in total will be downloaded to a local file");
                    break;
                case RESPONSE_BYTE_TRANSFER_EVENT:
                    this.bytesRead += bytes;
                    if (this.totalBytes != -1) {
                        int percent = (int) (this.bytesRead * 100.0 / this.totalBytes);
                        System.out.println(bytes + " bytes have been read at this time, download progress: " + percent
                                + "%(" + this.bytesRead + "/" + this.totalBytes + ")");
                    } else {
                        System.out.println(bytes + " bytes have been read at this time, download ratio: unknown" + "("
                                + this.bytesRead + "/...)");
                    }
                    break;
                case TRANSFER_COMPLETED_EVENT:
                    this.succeed = true;
                    System.out.println("Succeed to download, " + this.bytesRead + " bytes have been transferred in total");
                    break;
                case TRANSFER_FAILED_EVENT:
                    System.out.println("Failed to download, " + this.bytesRead + " bytes have been transferred");
                    break;
                default:
                    break;
            }
        }

        public boolean isSucceed() {
            return succeed;
        }
    }

    @Value("${config-8timer.environmental-science}")
    public String environmental_science;

    public void Logoutput(String science) {

        if (!("pro").equals(environmental_science)) {

            System.out.println(science);
        } else {
            System.out.println("");
        }

    }

    /**
     * @Author wgd
     * @Description 创建zip
     * @Date 2021/12/2 18:06
     **/
    public String createZip(Map<String, String> urlMap) throws IOException {
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = dateFormat.format(new Date()) + ".zip";
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        BufferedInputStream inputStream;
        OSSObject ossObject;
        String Suffix;
        try {
            File folder = new File(zipPath);
            if (!folder.exists() && !folder.isDirectory()) {
                folder.mkdirs();
            }
            fos = new FileOutputStream(zipPath + fileName);
            zos = new ZipOutputStream(fos);
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            for (String m : urlMap.keySet()) {
                Suffix = urlMap.get(m).substring(urlMap.get(m).lastIndexOf("."));
                ossObject = ossClient.getObject(bucketName, urlMap.get(m));
                inputStream = new BufferedInputStream(ossObject.getObjectContent());
                ZipEntry entry = new ZipEntry(m + Suffix);
                try {
                    zos.putNextEntry(entry);
                    int nNumber;
                    byte[] buffer = new byte[4096];
                    while ((nNumber = inputStream.read(buffer)) > 0) {
                        zos.write(buffer, 0, nNumber);
                    }
                } catch (IOException e) {
                    throw new IOException("写入失败");//TODO 应作为自定义异常
                } finally {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        throw new IOException("关闭失败");//TODO 应作为自定义异常
                    }
                }
            }
            ossClient.shutdown();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            // 关闭创建的流对象
            try {
                if (zos != null) {
                    zos.closeEntry();
                    zos.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                throw new IOException("关闭失败");//TODO 应作为自定义异常
            }
        }
        return fileName;
    }

    /**
     * @Author wgd
     * @Description 获取OSS文件字符流
     * @Date 2021/12/2 18:06
     **/
    private Map getOssFileList(Map<String, String> urlMap) throws IOException {
        Map<String, InputStream> map = Maps.newHashMap();
        BufferedInputStream inputStream;
        OSSObject ossObject;
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        for (String m : urlMap.keySet()) {
            ossObject = ossClient.getObject(bucketName, urlMap.get(m));
            inputStream = new BufferedInputStream(ossObject.getObjectContent());
            String suffix = urlMap.get(m).substring(urlMap.get(m).lastIndexOf("."));
            map.put(m + urlMap.get(m), inputStream);
        }
        ossClient.shutdown();
        return map;
    }

    private Map getFtpFileList(Map<String, String> urlMap) throws IOException {
        Map<String, InputStream> map = Maps.newHashMap();
        InputStream inputStream;
        for (String m : urlMap.keySet()) {
            File file = new File(urlMap.get(m));
            inputStream = new FileInputStream(file);
            map.put(m, inputStream);
        }
        return map;
    }

    public String newZip(Map<String, String> ossMap, Map<String, String> ftpMap) throws IOException {
        Map<String, InputStream> ossNewMap = getOssFileList(ossMap);
        Map<String, InputStream> ftpNewMap = getFtpFileList(ftpMap);
        ossNewMap.putAll(ftpNewMap);
        DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = dateFormat.format(new Date()) + ".zip";
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        InputStream inputStream = null;
        for (String m : ossNewMap.keySet()) {

            ZipEntry entry = new ZipEntry(m);
            try {
                zos.putNextEntry(entry);
                int nNumber;
                byte[] buffer = new byte[4096];
                while ((nNumber = ossNewMap.get(m).read(buffer)) > 0) {
                    zos.write(buffer, 0, nNumber);
                }
            } catch (IOException e) {
                throw new IOException("写入失败");//TODO 应作为自定义异常
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw new IOException("关闭失败");//TODO 应作为自定义异常
                }
            }
        }
        return fileName;
    }

}