1. 程式人生 > 其它 >阿里雲 oss 物件儲存,上傳、下載、刪除、獲取檔案、檔案列表,文件預覽 demo

阿里雲 oss 物件儲存,上傳、下載、刪除、獲取檔案、檔案列表,文件預覽 demo

技術標籤:雜記阿里雲java

記錄程式碼,如有錯誤,希望大家能夠指出問題。

1.maven 依賴

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.10.2</version>
        </dependency>

        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>[4.4.9,5.0.0)</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-imm</artifactId>
            <optional>true</optional>
            <version>1.22.0</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.28</version>
            <scope>runtime</scope>
        </dependency>

    </dependencies>

</project>

2、controller

package com.example.demo.controller;

import com.aliyun.oss.model.ObjectListing;
import com.example.demo.config.OSSProperties;
import com.example.demo.utils.OSSUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class uploadPhoto {

    @RequestMapping("/hello")
    public String helloWorld() {
        return "nihao";
    }

    /**
     * 多圖片上傳
     *
     * @param fileList
     * @return
     */
    @RequestMapping("/uploads")
    public String checkList(List<MultipartFile> fileList) {
        String photoUrl = "";
        OSSUtil ossClient = new OSSUtil();
        try {
            for (int i = 0; i < fileList.size(); i++) {
                //將檔案上傳
                String name = ossClient.uploadImg2Oss(fileList.get(i));
                //獲取檔案的URl地址  以便前臺  顯示
                String imgUrl = ossClient.getImgUrl(name);
                if (i == 0) {
                    photoUrl = imgUrl;
                } else {
                    photoUrl += "," + imgUrl;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return photoUrl.trim();
    }

    /**
     * 單檔案上傳
     *
     * @param imgFile
     * @param req
     * @return
     * @throws Exception
     */
    @RequestMapping("/upload")
    public Map<String, Object> uploadPhoto(@RequestParam("imgFile") MultipartFile imgFile, HttpServletRequest req) {
        OSSUtil ossClient = new OSSUtil();
        Map<String, Object> m = new HashMap<>();
        if (imgFile.isEmpty()) {
            m.put("error", "上傳檔案不能為空");
        }
        String newsUrl = "";
        if (!(imgFile).isEmpty()) {
            try {
                //將檔案上傳
                String name = ossClient.uploadImg2Oss(imgFile);
                //獲取檔案的URl地址  以便前臺  顯示
                String imgUrl = ossClient.getImgUrl(name);

                m.put("url", imgUrl);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            m.put("error", "上傳圖片不可為空");
        }
        return m;
    }

    /**
     * 獲取oss檔案
     *
     * @param key
     * @return
     */
    @RequestMapping("/onlineSee")
    public Map<String, Object> onlineSee(String key) {
        OSSUtil ossClient = new OSSUtil();
        Map<String, Object> m = new HashMap<>();
        String strings = ossClient.onlineSee(key);
        m.put("url", strings);
        return m;
    }

    /**
     * 文件預覽
     *
     * @param key
     * @return
     */
    @RequestMapping("/onlinePreview")
    public Map<String, Object> onlinePreview(String key) {
        OSSUtil ossClient = new OSSUtil();
        Map<String, Object> m = new HashMap<>();
        Object strings = ossClient.onlinePreview(key);
        m.put("url", strings);
        return m;
    }

    /**
     * 獲取檔案
     *
     * @param key
     * @return
     */
    @RequestMapping("/getUrl")
    public Map<String, Object> getUrl(String key) {
        OSSUtil ossClient = new OSSUtil();
        Map<String, Object> m = new HashMap<>();
        String strings = ossClient.getUrl(key);
        m.put("url", strings);
        return m;
    }

    /**
     * 獲取資料夾
     *
     * @param fileName
     * @return
     */
    @RequestMapping("/fileFolder")
    public Map<String, Object> fileFolder(String fileName) {
        Map<String, Object> m = new HashMap<>();
        OSSUtil ossClient = new OSSUtil();
        List<String> strings = ossClient.fileFolder(fileName);
        m.put("fileFolder", strings);
        return m;
    }

    /**
     * 通過檔名下載檔案
     *
     * @param objectName
     * @param localFileName
     * @return
     */
    @RequestMapping(value = "/downloadFile", method = RequestMethod.GET)
    public void downloadFile( HttpServletResponse response, String objectName, String localFileName) {
        try {
            OSSUtil ossClient = new OSSUtil();
            ossClient.downloadFile(response, objectName, localFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 刪除檔案
     *
     * @param key
     * @return
     */
    @RequestMapping(value = "/deleteObject", method = RequestMethod.POST)
    public void deleteObject(String key) {
        try {
            OSSUtil ossClient = new OSSUtil();
            ossClient.delFile(key);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 獲取資料夾下檔案列表
     *
     * @param fileHost
     * @return
     */
    @RequestMapping("/listFile")
    public Map<String, Object> listFile(String fileHost, String nextMarker) {
        OSSUtil ossClient = new OSSUtil();
        Map<String, Object> m = new HashMap<>();
        List<String> strings = ossClient.listFile(fileHost, nextMarker);
        m.put("listFile", strings);
        return m;
    }

    /**
     * 獲取資料夾下檔案列表和資料夾
     *
     * @param fileHost
     * @return
     */
    @RequestMapping("/listFile2")
    public Map<String, Object> listFile2(String fileHost, String nextMarker) {
        OSSUtil ossClient = new OSSUtil();
        Map<String, Object> m = new HashMap<>();
        ObjectListing strings = ossClient.listFile2(fileHost, nextMarker);
        m.put("listFile", strings);
        return m;
    }

    /**
     * 建立資料夾
     *
     * @param folder
     * @return
     */
    @RequestMapping("/createFolder")
    public Map<String, Object> createFolder(String folder) {
        Map<String, Object> m = new HashMap<>();
        try {
            OSSUtil ossClient = new OSSUtil();
            String reFolder = ossClient.createFolder(folder);
            m.put("reFolder", reFolder);
        } catch (Exception e) {
            e.printStackTrace();
            m.put("error", "請輸入檔名");
        }
        return m;
    }

    /**
     * 後臺提供獲取secretAccessKey,accessKeyId介面
     *
     * @param
     * @return
     */
    @RequestMapping("/ossConfig")
    public Map<String, Object> ossConfig() {
        Map<String, Object> m = new HashMap<>();
        try {
            String aliyunAccessKey = OSSProperties.ALIYUN_ACCESS_KEY;
            String aliyunAccessId = OSSProperties.ALIYUN_ACCESS_ID;
            m.put("aliyunAccessKey", aliyunAccessKey);
            m.put("aliyunAccessId", aliyunAccessId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return m;
    }


}

3、工具類

package com.example.demo.utils;

import com.alibaba.druid.util.StringUtils;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import com.example.demo.config.OSSProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

public class OSSUtil {

    /**
     * log日誌
     */
    public static final Logger logger = LoggerFactory.getLogger(OSSUtil.class);

    private static final String endpoint = OSSProperties.ALIYUN_ENDPOINT;
    private static final String accessKeyId = OSSProperties.ALIYUN_ACCESS_ID;
    private static final String accessKeySecret = OSSProperties.ALIYUN_ACCESS_KEY;
    private static final String bucketName = OSSProperties.ALIYUN_BUCKET;
    private static final String FOLDER = OSSProperties.ALIYUN_DIR;

    /**
     * 獲取oss
     *
     * @return
     */
    public static OSS getOSSClient() {
        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 上傳圖片
     *
     * @param url
     * @throws
     */
    public void uploadImg2Oss(String url) throws IOException {
        File fileOnServer = new File(url);
        FileInputStream fin;
        try {
            fin = new FileInputStream(fileOnServer);
            String[] split = url.split("/");
            this.uploadFile2OSS(fin, split[split.length - 1]);
        } catch (FileNotFoundException e) {
            throw new IOException("圖片上傳失敗");
        }
    }

    public String uploadImg2Oss(MultipartFile file) throws IOException {
       /* if (file.getSize() > 10 * 1024 * 1024) {
            throw new IOException("上傳圖片大小不能超過10M!");
        }*/
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        Random random = new Random();
        String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
        System.out.println(System.currentTimeMillis());
        System.out.println(name);
        System.out.println(random.nextInt(10000));
//        name = DateUtils.dateStr(new Date(), "yyyy/MM/dd") + "/" + System.currentTimeMillis() + substring;
        try {
            InputStream inputStream = file.getInputStream();
            this.uploadFile2OSS(inputStream, name);
            return name;
        } catch (Exception e) {
            e.printStackTrace();
            throw new IOException("圖片上傳失敗");
        }
    }

    /**
     * 獲得圖片路徑
     *
     * @param fileUrl
     * @return
     */
    public String getImgUrl(String fileUrl) {
        System.out.println(fileUrl);
        if (!StringUtils.isEmpty(fileUrl)) {
            String[] split = fileUrl.split("/");
            return this.getUrl(this.FOLDER + split[split.length - 1]);
        }
        return "";
    }

    /**
     * 上傳到OSS伺服器 如果同名檔案會覆蓋伺服器上的
     *
     * @param instream 檔案流
     * @param fileName 檔名稱 包括字尾名
     * @return 出錯返回"" ,唯一MD5數字簽名
     */
    public String uploadFile2OSS(InputStream instream, String fileName) {

        String ret = "";
        try {
            OSS ossClient = getOSSClient();
            // 建立上傳Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setContentType(getContentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setHeader("Pragma", "no-cache");
//            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            // 上傳檔案
            PutObjectResult putResult = ossClient.putObject(bucketName, FOLDER + fileName, instream, objectMetadata);
            ret = putResult.getETag();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    /**
     * 通過檔名判斷並獲取OSS服務檔案上傳時檔案的contentType
     *
     * @param filenameExtension 檔名
     * @return 檔案的contentType
     */
    public static final String getContentType(String filenameExtension) {

        if (filenameExtension.equalsIgnoreCase(".bmp")) {
            return "application/x-bmp";
        }
        if (filenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (filenameExtension.equalsIgnoreCase(".jpeg") ||
                filenameExtension.equalsIgnoreCase(".jpg") ||
                filenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpg";
        }
        if (filenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (filenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (filenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (filenameExtension.equalsIgnoreCase(".pptx") ||
                filenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (filenameExtension.equalsIgnoreCase(".docx") ||
                filenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (filenameExtension.equalsIgnoreCase(".xla") ||
                filenameExtension.equalsIgnoreCase(".xlc") ||
                filenameExtension.equalsIgnoreCase(".xlm") ||
                filenameExtension.equalsIgnoreCase(".xls") ||
                filenameExtension.equalsIgnoreCase(".xlt") ||
                filenameExtension.equalsIgnoreCase(".xlw")) {
            return "application/vnd.ms-excel";
        }
        if (filenameExtension.equalsIgnoreCase(".xlsx")) {
            return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        }
        if (filenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        if (filenameExtension.equalsIgnoreCase(".pdf")) {
            return "application/pdf";
        }
        if (filenameExtension.equalsIgnoreCase(".zip")) {
            return "application/zip";
        }
        if (filenameExtension.equalsIgnoreCase(".tar")) {
            return "application/x-tar";
        }
        if (filenameExtension.equalsIgnoreCase(".avi")) {
            return "video/avi";
        }
        if (filenameExtension.equalsIgnoreCase(".mp4")) {
            return "video/mpeg4";
        }
        if (filenameExtension.equalsIgnoreCase(".mp3")) {
            return "audio/mp3";
        }
        if (filenameExtension.equalsIgnoreCase(".mp2")) {
            return "audio/mp2";
        }
        // 預設下載
//        return "application/octet-stream";
        return "image/jpg";
    }


    /**
     * 獲得url連結
     *
     * @param key
     * @return
     */
    public String getUrl(String key) {
        // 設定URL過期時間為10年 3600l* 1000*24*365*10
        OSS ossClient = getOSSClient();
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        if (url != null) {
            String host = "https://" + url.getHost() + url.getPath();
            return host;
        }
        return "";
    }

    /**
     * 獲取資料夾
     *
     * @param fileName
     * @return
     */
    public List<String> fileFolder(String fileName) {
        // 建立OSSClient例項。
        OSS ossClient = getOSSClient();
        // 構造ListObjectsRequest請求。
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);

        // 設定正斜線(/)為資料夾的分隔符。
        listObjectsRequest.setDelimiter("/");
        // 設定prefix引數來獲取fun目錄下的所有檔案。
        if (!StringUtils.isEmpty(fileName)) {
            listObjectsRequest.setPrefix(fileName + "/");
        }
        // 列出檔案
        ObjectListing listing = ossClient.listObjects(listObjectsRequest);
        // 遍歷所有commonPrefix
        List<String> list = new ArrayList<>();
        for (String commonPrefix : listing.getCommonPrefixes()) {
            String newCommonPrefix = commonPrefix.substring(0, commonPrefix.length() - 1);
            String[] s = newCommonPrefix.split("/");
            if (!StringUtils.isEmpty(fileName)) {
                list.add(s[s.length - 1]);
            } else {
                list.add(s[0]);
            }
        }
        // 關閉OSSClient
        ossClient.shutdown();
        return list;
    }

    /**
     * 列舉檔案下所有的檔案url資訊
     */
    public ObjectListing listFile2(String fileHost, String nextMarker) {
        // 建立OSSClient例項。
        OSS ossClient = getOSSClient();

        // 構造ListObjectsRequest請求。
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);

        // 設定正斜線(/)為資料夾的分隔符。
        listObjectsRequest.setDelimiter("/");
        // 列出fun目錄下的所有檔案和資料夾。
        listObjectsRequest.setPrefix(fileHost + "/");

        ObjectListing listing = ossClient.listObjects(listObjectsRequest);

        // 遍歷所有檔案。
        System.out.println("Objects:");
        // objectSummaries的列表中給出的是fun目錄下的檔案。
        for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
            System.out.println(objectSummary.getKey());
        }

        // 遍歷所有commonPrefix。
        System.out.println("\nCommonPrefixes:");
        // commonPrefixs列表中顯示的是fun目錄下的所有子資料夾。由於fun/movie/001.avi和fun/movie/007.avi屬於fun資料夾下的movie目錄,因此這兩個檔案未在列表中。
        for (String commonPrefix : listing.getCommonPrefixes()) {
            System.out.println(commonPrefix);
        }

        // 關閉OSSClient。
        ossClient.shutdown();
        return listing;
    }

    /**
     * 列舉檔案下所有的檔案url資訊
     */
    public List<String> listFile(String fileHost, String nextMarker) {
        // 建立OSSClient例項。
        OSS ossClient = getOSSClient();
        // 構造ListObjectsRequest請求
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);

        // 設定prefix引數來獲取fun目錄下的所有檔案。
        listObjectsRequest.setPrefix(fileHost + "/");
        listObjectsRequest.setMarker(nextMarker);

        // 列出檔案。
        ObjectListing listing = ossClient.listObjects(listObjectsRequest);
        // 遍歷所有檔案。
        List<String> list = new ArrayList<>();
        for (int i = 0; i < listing.getObjectSummaries().size(); i++) {
            String FILE_URL = "https://" + bucketName + "." + endpoint + "/" + listing.getObjectSummaries().get(i).getKey();
            list.add(FILE_URL);
        }
        // 關閉OSSClient。
        ossClient.shutdown();


//        ObjectListing objectListing = null;
//        int total = 0;
//        HashMap<Integer, String> markerMap = new HashMap<>();
//        try {
//            ObjectListing objectListing2 = null;
//            do {
//                String nextMarker2 = objectListing2 != null ? objectListing2.getNextMarker() : null;
//                ListObjectsRequest listObjectsRequest2 = new ListObjectsRequest(bucketName).withMarker(nextMarker2).withMaxKeys(100);
//                listObjectsRequest2.setPrefix(fileHost + "/");
//                objectListing2 = ossClient.listObjects(listObjectsRequest2);
//                total += (objectListing2 != null && objectListing2.getObjectSummaries() != null ? objectListing2.getObjectSummaries().size() : 0);
//                markerMap.put(markerMap.size() + 1, nextMarker2);
//            } while (objectListing2 != null && !StringUtils.isEmpty(objectListing2.getNextMarker()));
//
//            ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName).withMarker(nextMarker).withMaxKeys(100);
//
//            listObjectsRequest.setPrefix(fileHost + "/");
//
//            objectListing = ossClient.listObjects(listObjectsRequest);
//            for (int i = 0; i < objectListing.getObjectSummaries().size(); i++) {
//                String FILE_URL = "https://" + bucketName + "." + endpoint + "/" + objectListing.getObjectSummaries().get(i).getKey();
//                list.add(FILE_URL);
//            }
//
//        } catch (Exception e) {
//
//        } finally {
//            // 關閉client
//            ossClient.shutdown();
//        }

        return list;
    }

    /**
     * 刪除檔案
     * objectName key 地址
     *
     * @param filePath
     */
    public Boolean delFile(String filePath) {
        // 建立OSSClient例項。
        OSS ossClient = getOSSClient();
        // 刪除Object.
        boolean exist = ossClient.doesObjectExist(bucketName, filePath);
        if (!exist) {
            return false;
        }
        ossClient.deleteObject(bucketName, filePath);
        ossClient.shutdown();
        return true;
    }

    /**
     * 批量刪除
     *
     * @param keys
     */
    public Boolean delFileList(List<String> keys) {
        // 建立OSSClient例項。
        OSS ossClient = getOSSClient();
        try {
            // 刪除檔案。
            DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(keys));
            List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            ossClient.shutdown();
        }
        return true;

    }

    /**
     * 建立資料夾
     *
     * @param folder
     * @return
     */
    public String createFolder(String folder) {
        // 建立OSSClient例項。
        OSS ossClient = getOSSClient();
        // 資料夾名
        final String keySuffixWithSlash = folder;
        // 判斷資料夾是否存在,不存在則建立
        if (!ossClient.doesObjectExist(bucketName, keySuffixWithSlash)) {
            // 建立資料夾
            ossClient.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));
            // 得到資料夾名
            OSSObject object = ossClient.getObject(bucketName, keySuffixWithSlash);
            String fileDir = object.getKey();
            ossClient.shutdown();
            return fileDir;
        }
        return keySuffixWithSlash;
    }

    /**
     * 通過檔名下載檔案
     *
     * @param objectName    要下載的檔名
     * @param localFileName 本地要建立的檔名
     */
    public void downloadFile(HttpServletResponse response, String objectName, String localFileName) throws Exception {
        // 建立OSSClient例項。
        OSS ossClient = getOSSClient();
        try {
            // ossObject包含檔案所在的儲存空間名稱、檔名稱、檔案元資訊以及一個輸入流。
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            // 讀去Object內容  返回
            BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());

            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            //通知瀏覽器以附件形式下載
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(objectName, "utf-8"));
            //BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(new File("f:\\a.txt")));
            byte[] car = new byte[1024];
            int L = 0;
            while ((L = in.read(car)) != -1) {
                out.write(car, 0, L);

            }
            if (out != null) {
                out.flush();
                out.close();
            }
            if (in != null) {
                in.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 關閉OSSClient。
            ossClient.shutdown();
        }
    }

    public String onlineSee(String key) {
        // 建立OSSClient例項。
        OSS ossClient = getOSSClient();
        // 設定URL過期時間為1小時
        Date expiration = new Date(new Date().getTime() + 3600 * 1000);
        // 臨時地址
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        // 關閉OSSClient。
        ossClient.shutdown();
        return url.toString();
    }

    public Object onlinePreview(String key) {
        // 建立OSSClient例項。
        OSS ossClient = getOSSClient();

        // 設定視訊截幀操作。文件頁數預設是200,EndPage_-1任意
        String style = "imm/previewdoc,EndPage_-1";

        String filenameExtension = key.substring(key.lastIndexOf("."));
        if (filenameExtension.equalsIgnoreCase(".pdf")) {
            style = "imm/previewdoc,EndPage_-1,PdfVector_true";
        }
        // 指定過期時間為1小時。
        Date expiration = new Date(new Date().getTime() + 1000 * 60 * 60);
        GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, key, HttpMethod.GET);
        req.setExpiration(expiration);
        req.setProcess(style);
        URL signedUrl = ossClient.generatePresignedUrl(req);

        return signedUrl;
    }


    public static void main(String[] args) {

    }

}

3、配置類

package com.example.demo.config;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource("classpath:/aliyun.properties")
public class OSSProperties implements InitializingBean {

    @Value("${aliyun.endpoint}")
    private String aliyun_endpoint;
    @Value("${aliyun.access-id}")
    private String aliyun_access_id;
    @Value("${aliyun.access-key}")
    private String aliyun_access_key;
    @Value("${aliyun.bucket}")
    private String aliyun_bucket;
    @Value("${aliyun.dir}")
    private String aliyun_dir;



    //宣告靜態變數,
    public static String ALIYUN_ENDPOINT;
    public static String ALIYUN_ACCESS_ID;
    public static String ALIYUN_ACCESS_KEY;
    public static String ALIYUN_BUCKET;
    public static String ALIYUN_DIR;



    @Override
    public void afterPropertiesSet() throws Exception {
        ALIYUN_ENDPOINT = aliyun_endpoint;
        ALIYUN_ACCESS_ID = aliyun_access_id;
        ALIYUN_ACCESS_KEY = aliyun_access_key;
        ALIYUN_BUCKET = aliyun_bucket;
        ALIYUN_DIR = aliyun_dir;
    }
}

4、阿里雲配置資料

aliyun.access-id=
aliyun.access-key=
aliyun.bucket=
aliyun.endpoint=
aliyun.dir=