1. 程式人生 > 其它 >amazonS3檔案管理工具類

amazonS3檔案管理工具類

/**
 * @author huaxu
 * @create 2018/12/10
 * @since 1.0.0
 */
public class AmazonS3Manager {
 
	public static final Logger logger = LoggerFactory.getLogger(AmazonS3Manager.class);
 
	private static String AMAZON_ENDPOINT_URL;
	private static String AMAZON_AWS_ACCESS_KEY;
	private static String AMAZON_AWS_SECRET_KEY;
 
	static {
 
		try {
			AMAZON_ENDPOINT_URL = String.valueOf(PropertyConfigurerUtils.getPropertyValueByKey("amazon.endpoint.url"));
			AMAZON_AWS_ACCESS_KEY = String.valueOf(PropertyConfigurerUtils.getPropertyValueByKey("amazon.access.key"));
			AMAZON_AWS_SECRET_KEY = String.valueOf(PropertyConfigurerUtils.getPropertyValueByKey("amazon.secret.key"));
 
		} catch (Exception e) {
			logger.error("amazonS3檔案伺服器基礎引數加載出錯" + e.getMessage());
		}
		logger.info("amazonS3 檔案伺服器基礎引數載入完成 access_key="+AMAZON_AWS_ACCESS_KEY + " endpoint_url="+AMAZON_ENDPOINT_URL);
	}
 
 
	/**
	 * 初始化連線,每次使用需要重新連線
	 */
	public static AmazonS3 initAmazonS3(){
 
		AmazonS3 s3 = new AmazonS3Client(new BasicAWSCredentials(AMAZON_AWS_ACCESS_KEY, AMAZON_AWS_SECRET_KEY));
		s3.setRegion(Region.getRegion(Regions.CN_NORTH_1));
		s3.setEndpoint(AMAZON_ENDPOINT_URL);
		s3.setS3ClientOptions(S3ClientOptions.builder().setPathStyleAccess(true).build());
		return s3;
	}
 
	/**
	 * 上傳檔案
	 * @param bucketName 桶名
	 * @param tempFile	待上傳檔案
	 * @param remoteFileName 檔名
	 * @return
	 */
	public static boolean uploadToS3(String bucketName, File tempFile, String remoteFileName, CannedAccessControlList fileType) {
 
		try {
			AmazonS3 s3 = initAmazonS3();
 
			if(!s3.doesBucketExistV2(bucketName)){
				s3.createBucket(bucketName);
			}
			s3.putObject(new PutObjectRequest(bucketName, remoteFileName, tempFile).withCannedAcl(fileType));
			return true;
		} catch (Exception ase) {
			logger.error("amazonS3上傳檔案File模式異常 " + ase.getMessage(), ase);
		}
		return false;
	}
 
	/**
	 * 上傳檔案
	 * @param bucketName 桶名
	 * @param multipartFile 待上傳檔案
	 * @param remoteFileName 檔名
	 * @return
	 */
	public static boolean uploadToS3(String bucketName, CommonsMultipartFile multipartFile, String remoteFileName, CannedAccessControlList fileType) {
 
		InputStream in = null;
		try {
			AmazonS3 s3 = initAmazonS3();
			in = multipartFile.getInputStream();
			FileItem fileItem = multipartFile.getFileItem();
 
			if(!s3.doesBucketExistV2(bucketName)){
				s3.createBucket(bucketName);
			}
			ObjectMetadata omd = new ObjectMetadata();
			omd.setContentType(fileItem.getContentType());
			omd.setContentLength(fileItem.getSize());
			omd.setHeader("filename", fileItem.getName());
 
			s3.putObject(new PutObjectRequest(bucketName, remoteFileName, in, omd).withCannedAcl(fileType));
			return true;
 
		} catch (Exception ase) {
			logger.error("amazonS3上傳檔案InputStream模式異常 " + ase.getMessage(), ase);
 
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					logger.error("amazonS3上傳檔案 關閉InputStream流異常 " + e.getMessage(), e);
				}
			}
		}
		return false;
	}
 
 
 
	/**
	 * 下載檔案
	 * @param bucketName	桶名
	 * @param remoteFileName	檔名
	 * @param path	下載路徑
	 */
	public static boolean downFromS3(String bucketName, String remoteFileName, String path) {
		try {
			AmazonS3 s3 = initAmazonS3();
 
			GetObjectRequest request  = new GetObjectRequest(bucketName,remoteFileName);
			s3.getObject(request,new File(path));
			return true;
		} catch (Exception ase) {
			logger.error("amazonS3下載檔案異常 " + ase.getMessage(), ase);
		}
		return false;
	}
 
 
	/**
	 * 刪除檔案
	 * @param bucketName	桶名
	 * @param remoteFileName	待刪除檔名
	 * @throws IOException
	 */
	public static void delFromS3(String bucketName, String remoteFileName) {
		try {
			AmazonS3 s3 = initAmazonS3();
			s3.deleteObject(bucketName, remoteFileName);
		} catch (Exception ase) {
			logger.error("amazonS3刪除檔案異常 " + ase.getMessage(), ase);
		}
	}
 
 
 
 
 
	/**
	 * 獲取短連結 帶過期時間
	 * @param bucketName	桶名稱
	 * @param remoteFileName	檔名稱
	 * @param expiration	過期時間/秒
	 */
	public static String getUrlFromS3(String bucketName, String remoteFileName, int expiration) {
		try {
			AmazonS3 s3 = initAmazonS3();
			GeneratePresignedUrlRequest httpRequest = new GeneratePresignedUrlRequest(bucketName, remoteFileName);
			httpRequest.setExpiration(new Date(new Date().getTime() + expiration * 1000));
 
			URL url = s3.generatePresignedUrl(httpRequest);
			return String.valueOf(url);
		} catch (Exception e) {
			logger.error("amazonS3獲取臨時連結異常 " + e.getMessage(), e);
		}
		return null;
	}
 
	/**
	 * 獲取永久連結
	 * @param bucketName	桶名稱
	 * @param remoteFileName	檔名稱
	 */
	public static String getUrlFromS3(String bucketName, String remoteFileName) {
 
		String url = "";
		try {
			AmazonS3 s3 = initAmazonS3();
			GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucketName, remoteFileName);
 
			url = String.valueOf(s3.generatePresignedUrl(urlRequest)).split("\\?")[0];
			if (url.indexOf(remoteFileName) == -1) {
				throw new RuntimeException("url檔名稱校驗不合法");
			}
			return url;
 
		} catch (Exception e) {
			logger.error("amazonS3獲取永久連結異常 " + e.getMessage(), e);
			return "";
		}
	}
 
	public static AmazonS3 getS3(){
		return initAmazonS3();
	}
 
	/**
	 * 根據桶名稱獲取檔案集合
	 */
	public static List<S3ObjectSummary> getFileMsgByBucketName(String bucketName){
		AmazonS3 s3 = initAmazonS3();
		ObjectListing objectListing = s3.listObjects(bucketName);
		List<S3ObjectSummary> objectSummaries = objectListing.getObjectSummaries();
		return objectSummaries;
	}
}

  

每天學習一點點,你就進步一點點。