当前位置:   article > 正文

S3 对象存储,实现图片上传功能_java s3对象存储

java s3对象存储

S3 对象存储,实现图片上传功能


1.maven 依赖

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk</artifactId>
    <version>1.12.410</version>
</dependency>
  • 1
  • 2
  • 3
  • 4
  • 5

2.S3 工具类

@Slf4j
@Component
public class S3Manager {

    /**
     *         <dependency>
     *             <groupId>com.amazonaws</groupId>
     *             <artifactId>aws-java-sdk</artifactId>
     *             <version>1.12.410</version>
     *         </dependency>
     */

	//access_key
    private static final String AWS_ACCESS_KEY = "QTR19VOU2J3HC9U2ZB8W";

	//secret_key
    private static final String AWS_SECRET_KEY = "gs2Kr2efO6ttkOyq9BPPXwThyJ4PjBy7PBQPxOJZ";

	//S3 的 ip:端口号
    private static final String ENDPOINT = "https://ip:端口号";

	//木桶名称
    private static final String DEFAULT_BUCKETNAME = "xxxxx";

    private static volatile AmazonS3 amazonClient = null;

    static {
        S3Manager s3Manager = new S3Manager();
        s3Manager.getAmazonClient();
    }
    private AmazonS3 getAmazonClient() {
        if(amazonClient == null) {
            synchronized (S3Manager.class) {
                if (amazonClient == null) {
                    // AWS连接云平台
                    AWSCredentials credentials = new BasicAWSCredentials(AWS_ACCESS_KEY, AWS_SECRET_KEY);
                    ClientConfiguration clientConfig = new ClientConfiguration();
                    clientConfig.setProtocol(Protocol.HTTP);

                    AmazonS3 conn = AmazonS3ClientBuilder.standard()
                            .withClientConfiguration(clientConfig)
                            .withCredentials(new AWSStaticCredentialsProvider(credentials))
                            .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(ENDPOINT, ""))
                            .withPathStyleAccessEnabled(true)
                            .build();
                    amazonClient = conn;
                }
            }
        }
        return amazonClient;
    }



    /**
     *上传
     * @param bucket
     * @param file
     * @param fileKey
     * @return
     */
    public static PutObjectResult uploadFile(String bucket, File file, String fileKey) {
        PutObjectRequest request = new PutObjectRequest(bucket, fileKey, file);
        return amazonClient.putObject(request);
    }

    /**
     * 上传
     * @param bucketName
     * @param multipartFile
     * @param fileKey
     * @return
     * @throws IOException
     */
    public static PutObjectResult uploadFile(String bucketName, MultipartFile multipartFile, String fileKey) throws IOException {
        return uploadFile(bucketName, multipartFile.getInputStream(), multipartFile.getSize(), multipartFile.getContentType(), fileKey);
    }

    /**
     * 上传
     * @param bucketName
     * @param fileInput
     * @param contentLength
     * @param fileContentType
     * @param fileKey
     * @return
     */
    public static PutObjectResult uploadFile(String bucketName, InputStream fileInput, Long contentLength, String fileContentType, String fileKey) {
        PutObjectRequest request = new PutObjectRequest(bucketName, fileKey, fileInput, null);
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(contentLength);
        if (StrUtil.isNotBlank(fileContentType)) {
            metadata.setContentType(fileContentType);
            request.setMetadata(metadata);
        }

        GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucketName, fileKey);
        urlRequest.setExpiration(null);
        URL url = amazonClient.generatePresignedUrl(urlRequest);
        log.info("[s3文件上传文件路径]----》url:{}",url);

        return amazonClient.putObject(request);
    }

    /**
     *  wangmx
     * @param bucketName 木头名称
     * @param multipartFile file 上传的文件
     * @param fileKey 文件唯一标识符(文件名称)
     * @return url 图片访问路径
     * @throws IOException
     */
    public static String uploadFileGetUrl(String bucketName, MultipartFile multipartFile, String fileKey) throws IOException {
        InputStream fileInput = multipartFile.getInputStream();
        Long contentLength = multipartFile.getSize();
        String fileContentType = multipartFile.getContentType();

        PutObjectRequest request = new PutObjectRequest(bucketName, fileKey, fileInput, null).withCannedAcl(CannedAccessControlList.PublicRead);
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(contentLength);
        if (StrUtil.isNotBlank(fileContentType)) {
            metadata.setContentType(fileContentType);
            request.setMetadata(metadata);
        }
        PutObjectResult putObjectResult = amazonClient.putObject(request);


        // 打印所有 bucket
        List<Bucket> buckets = amazonClient.listBuckets();
        log.info("s3文件云平台存储桶列表,{}", buckets);


        //获取url  可行
//        GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucketName, fileKey);
//        urlRequest.setExpiration(null);
//        URL url = amazonClient.generatePresignedUrl(urlRequest);
        String url = ENDPOINT+"/"+bucketName+"/"+fileKey;
        log.info("[s3文件上传文件路径]----》url:{}",url);

        return url;
    }

    //下载
    public static InputStream downloadFile(String bucketName, String fileKey) {
        GetObjectRequest request = new GetObjectRequest(bucketName, fileKey);
        S3Object response = amazonClient.getObject(request);
        return response.getObjectContent();
    }

    public static void downloadFile(HttpServletRequest request, HttpServletResponse response, String bucketName, String fileKey) throws IOException {
        response.setContentType("application/force-download");// 设置强制下载不打开
        response.addHeader("Content-Disposition", "attachment;fileName=" + fileKey);// 设置文件名
        InputStream is = downloadFile(bucketName, fileKey);
        OutputStream os = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = is.read(buffer)) != -1) {
            os.write(buffer, 0, length);
        }
    }

    /**
     * 检查储存空间是否已创建,未创建便会创建
     */
    public static void checkBucket(String bucketName) {
        if (amazonClient.doesBucketExist(bucketName)) {
            log.warn("Storage s3 api, bucketName is found: " + bucketName);
        } else {
            log.warn("Storage s3 api, bucketName is not exist, create it: " + bucketName);
            amazonClient.createBucket(bucketName);
        }
    }

    /**
     * 获取所有的存储空间
     * @return
     */
    public static List<Bucket> getBucketList() {
        List<Bucket> buckets = amazonClient.listBuckets();
        for (Bucket bucket : buckets) {
            System.out.println(bucket.getName() + "\t" +
                    DateUtil.date(bucket.getCreationDate()));
        }
        return buckets;
    }

    /**
     * 删除存储空间
     * @param bucketName
     */
    public static void deleteBucket(String bucketName) {
        amazonClient.deleteBucket(bucketName);
    }

    public static ObjectListing getObjectListing(String bucketName) {
        ObjectListing objects = amazonClient.listObjects(bucketName);
        do {
            for (S3ObjectSummary objectSummary : objects.getObjectSummaries()) {
                log.info("\n文件名:" + objectSummary.getKey() + "\n" + "文件大小:" + objectSummary.getSize() + "\n" + "最后一次修改时间:" + DateUtil.date(objectSummary.getLastModified()));
            }
            objects = amazonClient.listNextBatchOfObjects(objects);
        } while (objects.isTruncated());
        return objects;
    }

    /**
     * 删除文件
     * @param bucketName
     * @param fileKey
     */
    public static void deleteObject(String bucketName, String fileKey) {
        amazonClient.deleteObject(bucketName, fileKey);
    }


    public static void main(String[] args) {
        checkBucket(DEFAULT_BUCKETNAME);
        //uploadFile("test".getBytes(),"fff");
        //getBucketList();
        //deleteObject(DEFAULT_BUCKETNAME,"1111");
        getObjectListing(DEFAULT_BUCKETNAME);
    }
}
  • 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

3.具体代码实现

@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation("上传")
	public Result upload(@RequestParam("file") MultipartFile file, HttpServletRequest req)throws Exception {
		Result result = new Result();
		S3Manager.checkBucket("yxf-bucket-01");
		//木桶名称 bucketName
		//文件名 fileKey
		//原文件名称
		String oldName = file.getOriginalFilename();
		String substring = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		//新文件名称
		String newName = IdWorker.get32UUID()+substring;

		//木桶名称 bucketName
		//文件名 fileKey
		String url = S3Manager.uploadFileGetUrl("xxxxx", file, newName);
		result.setData(url);
		return result.success();
	}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号