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

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


1.maven 依赖

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

2.S3 工具类

@Slf4j
@Component
public class S3Manager {

    /**
     *         
     *             com.amazonaws
     *             aws-java-sdk
     *             1.12.410
     *         
     */

	//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);
    }
}

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();
	}

你可能感兴趣的:(其他,java,servlet,开发语言)