Amazon S3生成預簽名URL,PDF文件可在線預覽

Utils

package com.foxconn.devops.common.s3;


import com.amazonaws.ClientConfiguration;
import com.amazonaws.HttpMethod;
import com.amazonaws.Protocol;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.*;
import jakarta.servlet.http.HttpServletResponse;
import lombok.val;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class AmazonFileUtils {
    private final static Logger logger = LoggerFactory.getLogger(AmazonFileUtils.class);
    /**
     * S3服务器地址
     */
    private  static String S3_URL;
    /**
     * 账号key
     */
    private  static String ACCESS_KEY;
    /**
     * 密码key
     */
    private  static String SECRET_KEY;

    private static String bucket;


    /**
     * 获取连接
     * @return
     * @throws Exception
     */
    public static AmazonS3 connectS3Client() throws Exception {
        URL url = new URL(S3_URL);
        ClientConfiguration config = new ClientConfiguration().withProtocol(Protocol.HTTP);
        AmazonS3 client = AmazonS3ClientBuilder.standard()
                .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(url.toString(), Regions.CN_NORTH_1.toString()))
                .withClientConfiguration(config)
                .withPathStyleAccessEnabled(true)
                .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY)))
                .build();
        return client;
    }


    public static String createPresignedGetUrl(String keyName)  {
        try {
            // 创建S3客户端
            AmazonS3 s3Client = connectS3Client();
            // 创建预签名请求
            GeneratePresignedUrlRequest generatePresignedUrlRequest =
                    new GeneratePresignedUrlRequest(bucket, keyName)
                            .withMethod(HttpMethod.GET);

            // 设置过期时间,例如1小时后
            long expirationTimeMinutes = 60;
            generatePresignedUrlRequest.setExpiration(new Date(System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(expirationTimeMinutes)));

            //修改訪問權限
            s3Client.setObjectAcl(bucket, keyName, CannedAccessControlList.PublicReadWrite);

            // 获取预签名URL
            URL presignedUrl = s3Client.generatePresignedUrl(generatePresignedUrlRequest);
            // 输出预签名URL
            System.out.println("Pre-Signed URL: " + presignedUrl.toString());
            return presignedUrl.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 下载
     * @return
     * @throws Exception
     */
    public static void downloadFile(String fileKey,String fileName, HttpServletResponse resp) throws Exception{
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("multipart/form-data");
        resp.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
        OutputStream outputStream = resp.getOutputStream();

        InputStream input = reLoadFile(fileKey);
        byte[] content = new byte[1024];
        int a = -1;
        while ((a = input.read(content))!=-1){
            outputStream.write(content,0,a);
        }
        input.close();
        outputStream.flush();
    }

    public static InputStream reLoadFile(String fileKey){
        AmazonS3 s3client = null;
        try {
            s3client = connectS3Client();
        } catch (Exception e) {
            e.printStackTrace();
        }
        GetObjectRequest request = new GetObjectRequest(bucket, fileKey);
        S3Object response = s3client.getObject(request);
        InputStream input = response.getObjectContent();
        return input;
     }

    /**
     * 删除文件
     * @param fileKey
     * @throws Exception
     */
    public static void deleteFile(String fileKey) throws Exception {
        AmazonS3 s3client = connectS3Client();
        DeleteObjectRequest request = new DeleteObjectRequest(bucket, fileKey);
        s3client.deleteObject(request);
    }

    /**
     * Bucket列表
     * @return
     * @throws Exception
     */
    public static List<Bucket> listFile() throws  Exception{
        AmazonS3 s3client = connectS3Client();
        ListBucketsRequest request = new ListBucketsRequest();
        List<Bucket> list = s3client.listBuckets(request);
        return list;
    }

    /**
     * 是否存在Bucket
     * @param bucketName
     * @return
     * @throws Exception
     */
    public static boolean isExistBucket(String bucketName) throws Exception{
        AmazonS3 s3client = connectS3Client();
        try {
            HeadBucketRequest request = new HeadBucketRequest(bucketName);
            s3client.headBucket(request);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 创建Bucket
     * @param bucketName
     * @return
     * @throws Exception
     */
    public static void createBucket(String bucketName) throws Exception{
        boolean isBucketExists = isExistBucket(bucketName);
        AmazonS3 s3client = null;
        if (!isBucketExists) {
            s3client = connectS3Client();
            CreateBucketRequest request = new CreateBucketRequest(bucketName);
            s3client.createBucket(request);
        }
    }

    /**
     * 删除Bucket
     * @param bucketName
     * @return
     * @throws Exception
     */
    public static void deleteBucket(String bucketName) throws Exception {
        AmazonS3 s3client = connectS3Client();
        DeleteBucketRequest request = new DeleteBucketRequest(bucketName);
        s3client.deleteBucket(request);
    }

    /**
     * fileKey是否存在
     * @param bucketName
     * @param fileKey
     * @return
     * @throws Exception
     */
    public static boolean isExistFileKey(String bucketName, String fileKey) throws  Exception{
        AmazonS3 s3client = connectS3Client();
        GetObjectRequest request = new GetObjectRequest(bucketName,fileKey);
        S3Object response = s3client.getObject(request);
        boolean result =  response != null &&  fileKey.equals(response.getKey());
        return result;
    }

    /**
     * fileKey是否存在
     * @param fileKey
     * @return
     * @throws Exception
     */
    public static boolean isExistFileKey(String fileKey) throws  Exception{
        AmazonS3 s3client = connectS3Client();
        GetObjectRequest request = new GetObjectRequest(AmazonFileUtils.bucket,fileKey);
        S3Object response = s3client.getObject(request);
        boolean result =  response != null &&  fileKey.equals(response.getKey());
        return result;
    }

    /**
     * 获取文件key
     * @param fileName
     * @return
     * @throws Exception
     */
    private static String getFileKey(String fileName) throws Exception{
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        String dateDir = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String fileType = fileName.substring(fileName.lastIndexOf(".")+1);
        String fileKey = uuid + "." + fileType.toLowerCase();
        return fileKey;
    }

    public static String uploadFile(MultipartFile file) throws Exception {
        try {
            if (file == null) {
                throw new RuntimeException("文件不能為空");
            }
            createBucket(bucket);
            String fileKey = getFileKey(file.getOriginalFilename());
            InputStream fileInputStream = file.getInputStream();
            val metadata = new ObjectMetadata();
            metadata.setContentLength(fileInputStream.available());
            metadata.setContentType(file.getContentType());
            // 创建ACL
            AccessControlList acl = new AccessControlList();
            acl.grantPermission(GroupGrantee.AllUsers, Permission.Read); // 允许所有人读取
            PutObjectRequest request = new PutObjectRequest(bucket, fileKey, fileInputStream, metadata).withAccessControlList(acl);
            AmazonS3 s3client = connectS3Client();

            s3client.putObject(request);
            return fileKey;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    public static void uploadPdfFile(String pdfFilePath, String fileKey) {
        try {
            File file = new File(pdfFilePath);
            if (file == null) {
                throw new RuntimeException("文件不能為空");
            }
            createBucket(bucket);
//            String fileKey = getFileKey(file.getOriginalFilename());
//            InputStream fileInputStream = file.getInputStream();
            InputStream fileInputStream = new FileInputStream(pdfFilePath);
            val metadata = new ObjectMetadata();
            metadata.setContentLength(fileInputStream.available());
            metadata.setContentType("application/pdf");
            // 创建ACL
            AccessControlList acl = new AccessControlList();
            acl.grantPermission(GroupGrantee.AllUsers, Permission.Read); // 允许所有人读取
            PutObjectRequest request = new PutObjectRequest(bucket, fileKey, fileInputStream, metadata).withAccessControlList(acl);
            AmazonS3 s3client = connectS3Client();
            s3client.putObject(request);
        } catch (Exception e) {
            e.printStackTrace();
//            throw e;
            logger.error("fileKey==" + fileKey + "==uploadPdfFile失敗:" + e.getMessage());
        }
    }

    public static String getPdfKey(String fileKey) {
        return fileKey.substring(0, fileKey.lastIndexOf(".")) + ".pdf";
    }


    @Value("${amazon.url}")
    public  void setS3Url(String s3Url) {
        S3_URL = s3Url;
    }
    @Value("${amazon.access.key}")
    public  void setAccessKey(String accessKey) {
        ACCESS_KEY = accessKey;
    }
    @Value("${amazon.secret.key}")
    public  void setSecretKey(String secretKey) {
        SECRET_KEY = secretKey;
    }
    @Value("${amazon.bucket}")
    public  void setBucket(String bucket) {
        AmazonFileUtils.bucket = bucket;
    }
}

預簽名URL可預覽而不是下載 需設置 文件類型 contentType

val metadata = new ObjectMetadata();
metadata.setContentLength(fileInputStream.available());
//設置文件類型 供瀏覽器識別展示預覽
metadata.setContentType(file.getContentType());
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,732评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,496评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,264评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,807评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,806评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,675评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,029评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,683评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,704评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,666评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,773评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,413评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,016评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,978评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,204评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,083评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,503评论 2 343

推荐阅读更多精彩内容