天天看點

檔案上傳oss

檔案上傳oss

api檢視

https://help.aliyun.com/document_detail/

jar包引入

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

其核心配置

// Endpoint以杭州為例,其它Region請按實際情況填寫。
String endpoint = "http://oss-cn-beijing.aliyuncs.com";
// 使用剛剛建立的accessKeyId和accessKeySecret
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";

// 建立OSSClient執行個體。
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
//todo 

// 關閉OSSClient。
ossClient.shutdown();
           

上傳檔案

配置檔案

ossConfig

package com.meeno.chemical.common.oss.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * Oss配置類
 * @author LGL
 * @date 2020/9/15 19:29
 */
@Configuration
public class OssConfig {
    /**
     * 地區
     */
    public static String region;
    /**
     * 通路密鑰Id
     */
    public static String accessKeyId;
    /**
     * 賬号密匙
     */
    public static String accessKeySecret;
    /**
     * 名稱
     */
    public static String bucket;

    @Value("${oss.region}")
    public void setRegion(String region) {
        OssConfig.region = region;
    }
    @Value("${oss.accessKeyId}")
    public void setAccessKeyId(String accessKeyId) {
        OssConfig.accessKeyId = accessKeyId;
    }
    @Value("${oss.accessKeySecret}")
    public void setAccessKeySecret(String accessKeySecret) {
        OssConfig.accessKeySecret = accessKeySecret;
    }
    @Value("${oss.bucket}")
    public void setBucket(String bucket) {
        OssConfig.bucket = bucket;
    }
}
           

其在yaml中的配置

oss:
  region: oss-cn-shanghai
  accessKeyId: **********
  accessKeySecret: *************
  bucket: *******
           

通過流的方式上傳檔案,傳回可以預覽圖檔的位址

/**
 * 通過流的方式上傳檔案,傳回可以預覽圖檔的位址
 * @param file
 * @return
 */
public static String uploadFilePreviewImageByStream(MultipartFile file){
    String bucketName = OssConfig.bucket;
    String endpoint = "http://" + OssConfig.region + ".aliyuncs.com";
    String accessKeyId = OssConfig.accessKeyId;
    String accessKeySecret = OssConfig.accessKeySecret;

    // 擷取檔案的字尾名
    String fileName = file.getOriginalFilename();
    String suffixName = fileName.substring(fileName.lastIndexOf("."));
    //生成上傳檔案名
    String finalFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + suffixName;

    // 生成存儲路徑
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    String objectName = sdf.format(new Date()) + "/" + finalFileName;

    //生成新的檔案
    File files;
    try (InputStream ins = file.getInputStream()) {
        files = new File(file.getOriginalFilename());
        inputStreamToFile(ins, files);
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, objectName, files);
        // 設定URL過期時間為1小時。
        Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);

        // 生成以GET方法通路的簽名URL,訪客可以直接通過浏覽器通路相關内容。
        URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
        log.info(url.toString());
        ossClient.shutdown();
    } catch (Exception e) {
        e.printStackTrace();
    }
    String url = "http://" + bucketName + "." + OssConfig.region + ".aliyuncs.com" + "/" + objectName;
    return url;
}

public static void inputStreamToFile(InputStream ins, File file) {
    try {
        OutputStream os = new FileOutputStream(file);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
           

通過上傳檔案位置的方式上傳檔案,傳回可以預覽檔案的位址

/**
 * 上傳檔案,傳回可以預覽檔案的位址
 * @param fullPath  "/Users/dalaoyang/Desktop/aliyun.jpeg"
 * @return
 */
public static String uploadFilePreviewImageByAddress(String fullPath) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    String endpoint = "http://" + OssConfig.region + ".aliyuncs.com";
    String accessKeyId = OssConfig.accessKeyId;
    String accessKeySecret = OssConfig.accessKeySecret;
    String fileName = fullPath;
    String bucketName = OssConfig.bucket;
    // 擷取檔案的字尾名
    String suffixName = fileName.substring(fileName.lastIndexOf("."));
    // 生成上傳檔案名
    String finalFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + suffixName;
    String objectName = sdf.format(new Date()) + "/" + finalFileName;
    File file = new File(fileName);
    OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

    ossClient.putObject(bucketName, objectName, file);
    // 設定URL過期時間為1小時。
    // Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);

    // 生成以GET方法通路的簽名URL,訪客可以直接通過浏覽器通路相關内容。
    // URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);

    ossClient.shutdown();
    String url = "http://" + bucketName + "." + OssConfig.region + ".aliyuncs.com" + "/" + objectName;
    return url;
}
           

通過上傳檔案位置的方式上傳檔案,傳回可以直接下載下傳檔案的位址

/**
 * 上傳檔案,傳回可以直接下載下傳檔案的位址
 * @param fullPath" /Users/dalaoyang/Desktop/aliyun.jpeg"
 * @return
 */
public static String uploadFileDownloadPictures(String fullPath) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    String bucketName = OssConfig.bucket;
    String endpoint = "http://" + OssConfig.region + ".aliyuncs.com";
    String accessKeyId = OssConfig.accessKeyId;
    String accessKeySecret = OssConfig.accessKeySecret;
    String fileName = fullPath;
    // 擷取檔案的字尾名
    String suffixName = fileName.substring(fileName.lastIndexOf("."));
    // 生成上傳檔案名
    String finalFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + suffixName;
    String objectName = sdf.format(new Date()) + "/" + finalFileName;
    File file = new File(fileName);

    ObjectMetadata meta = new ObjectMetadata();
    meta.setContentDisposition("attachment;");
    OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

    ossClient.putObject(bucketName, objectName, file, meta);
    // 設定URL過期時間為1小時。
    Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
    // 生成以GET方法通路的簽名URL,訪客可以直接通過浏覽器通路相關内容。
    URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
    ossClient.shutdown();
    return url.toString();
}
           

下載下傳多個 oss檔案并壓縮 zip

/**
     * 下載下傳多個 oss檔案并壓縮 zip
     * @param request
     * @param response
     * @param keys		檔案位址
     * @return
     */
    public static String getOssFile(HttpServletRequest request, HttpServletResponse response, List<String> keys) {
        String endpoint = "http://" + OssConfig.region + ".aliyuncs.com";
        String accessKeyId = OssConfig.accessKeyId;
        String accessKeySecret = OssConfig.accessKeySecret;
        String bucketName = OssConfig.bucket;
        try {
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            String fileName = "資料報告.zip";
            File zipFile = File.createTempFile("test", ".zip");
            FileOutputStream f = new FileOutputStream(zipFile);
            CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
            ZipOutputStream zos = new ZipOutputStream(csum);
            for (String ossfile : keys) {
            	//簡單處理檔案位址
                ossfile = ossfile.substring(endpoint.length() + 7, ossfile.lastIndexOf("?"));
                //處理檔案位址亂碼問題
                ossfile = URLDecoder.decode(ossfile, "UTF-8");
                OSSObject ossobject = ossClient.getObject(bucketName, ossfile);
                InputStream inputStream = ossobject.getObjectContent();
                //處理命名問題
                zos.putNextEntry(new ZipEntry(ossfile.split("/")[1]));
                int bytesRead;
                while ((bytesRead = inputStream.read()) != -1) {
                    zos.write(bytesRead);
                }
                inputStream.close();
                zos.closeEntry();
            }
            zos.close();
            String header = request.getHeader("User-Agent").toUpperCase();
            if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
                fileName = URLEncoder.encode(fileName, "utf-8");
                fileName = fileName.replace("+", "%20");
            } else {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            }
            response.reset();
            response.setContentType("text/plain");
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setHeader("Location", fileName);
            response.setHeader("Cache-Control", "max-age=0");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            FileInputStream fis = new FileInputStream(zipFile);
            BufferedInputStream buff = new BufferedInputStream(fis);
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            byte[] car = new byte[1024];
            int l = 0;
            while (l < zipFile.length()) {
                int j = buff.read(car, 0, 1024);
                l += j;
                out.write(car, 0, j);
            }
            fis.close();
            buff.close();
            out.close();

            ossClient.shutdown();
            System.out.println(zipFile.getName());
            zipFile.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }