java 阿里云oss上传工具类

工具类


import com.aliyun.oss.ClientException;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.utils.DateUtil;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.PutObjectRequest;
import org.apache.log4j.Logger;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.net.URL;
import java.text.ParseException;
import java.util.Date;

/**
 * @author cc
 */
public class OssUtils {
	private static Logger log = Logger.getLogger(OssUtils.class);
	private static String endpoint = ProperUtils.getString("endpoint");
	private static String accessKeyId = ProperUtils.getString("accessKeyId");
	private static String accessKeySecret = ProperUtils.getString("accessKeySecret");
	private static String bucketName = ProperUtils.getString("bucketName");


	//private static String key = "ADFSEHSJ";
	//private static String localFile = "D://temp/abc.jpg";
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//fileDelete("audio/2");
		//fileUpload(localFile, "a/cover/abc.jpg");
	}
	
	public static String fileUpload(String filePath, String fileRelaPath) {
		String fileUrl = "";
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		try {
			/*
			 * 上传一个对象到存储空间
			 */
			Date expiration = DateUtil.parseRfc822Date("Wed, 18 Mar 2118 16:18:00 GMT");
			GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(
					bucketName, fileRelaPath, HttpMethod.GET);
			// 设置过期时间
			request.setExpiration(expiration);
			// 生成URL签名(HTTP GET请求)
			URL signedUrl = ossClient.generatePresignedUrl(request);
			fileUrl = signedUrl.toString();
			File file = new File(filePath);
			ossClient.putObject(new PutObjectRequest(bucketName, fileRelaPath, file));
			//上传到OSS后删除本地文件
			file.delete();
			return fileUrl;
		} catch (OSSException oe) {
			log.info("Caught an OSSException, which means your request made it to OSS, "
							+ "but was rejected with an error response for some reason.");
			log.info("Error Message: " + oe.getErrorCode());
			log.info("Error Code:       " + oe.getErrorCode());
			log.info("Request ID:      " + oe.getRequestId());
			log.info("Host ID:           " + oe.getHostId());
		} catch (ClientException ce) {
			log.info("Caught an ClientException, which means the client encountered "
							+ "a serious internal problem while trying to communicate with OSS, "
							+ "such as not being able to access the network.");
			log.info("Error Message: " + ce.getMessage());
		} catch (ParseException e) {
			e.printStackTrace();
		} finally {
			ossClient.shutdown();
		}
		return fileUrl;
	}
	
	public static void fileDelete(String fileRelaPath) {
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		try {
			/*
			 * 从存储空间删除一个对象
			 */
			//判断文件是否存在
			ossClient.deleteObject(bucketName, fileRelaPath);

		} catch (OSSException oe) {
			log.info("Caught an OSSException, which means your request made it to OSS, "
							+ "but was rejected with an error response for some reason.");
			log.info("Error Message: " + oe.getErrorCode());
			log.info("Error Code:       " + oe.getErrorCode());
			log.info("Request ID:      " + oe.getRequestId());
			log.info("Host ID:           " + oe.getHostId());
		} catch (ClientException ce) {
			log.info("Caught an ClientException, which means the client encountered "
							+ "a serious internal problem while trying to communicate with OSS, "
							+ "such as not being able to access the network.");
			log.info("Error Message: " + ce.getMessage());
		} finally {
			ossClient.shutdown();
		}
	}
	
	public static String fileUploadBytes(byte[] bytes, String fileRelaPath) {
		String fileUrl = "";
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		try {
			/*
			 * 上传一个对象到存储空间
			 */
			Date expiration = DateUtil.parseRfc822Date("Wed, 18 Mar 2118 16:18:00 GMT");
			GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(
					bucketName, fileRelaPath, HttpMethod.GET);
			// 设置过期时间
			request.setExpiration(expiration);
			// 生成URL签名(HTTP GET请求)
			URL signedUrl = ossClient.generatePresignedUrl(request);
			fileUrl = signedUrl.toString();
			ossClient.putObject(bucketName, fileRelaPath, new ByteArrayInputStream(bytes));
			//上传到OSS后删除本地文件
			return fileUrl;
		} catch (OSSException oe) {
			log.info("Caught an OSSException, which means your request made it to OSS, "
							+ "but was rejected with an error response for some reason.");
			log.info("Error Message: " + oe.getErrorCode());
			log.info("Error Code:       " + oe.getErrorCode());
			log.info("Request ID:      " + oe.getRequestId());
			log.info("Host ID:           " + oe.getHostId());
		} catch (ClientException ce) {
			log.info("Caught an ClientException, which means the client encountered "
							+ "a serious internal problem while trying to communicate with OSS, "
							+ "such as not being able to access the network.");
			log.info("Error Message: " + ce.getMessage());
		} catch (ParseException e) {
			e.printStackTrace();
		} finally {
			ossClient.shutdown();
		}
		return fileUrl;
	}
	
	
	public static String getUploadFileUrl(String filePathName) {
		String fileUrl = "";
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		try {
			/*
			 * 上传一个对象到存储空间
			 */
			Date expiration = DateUtil.parseRfc822Date("Wed, 18 Mar 2118 16:18:00 GMT");
			GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(
					bucketName, filePathName, HttpMethod.GET);
			// 设置过期时间
			request.setExpiration(expiration);
			// 生成URL签名(HTTP GET请求)
			URL signedUrl = ossClient.generatePresignedUrl(request);
			return signedUrl.toString();
		} catch (OSSException oe) {
			log.info("Caught an OSSException, which means your request made it to OSS, "
							+ "but was rejected with an error response for some reason.");
			log.info("Error Message: " + oe.getErrorCode());
			log.info("Error Code:       " + oe.getErrorCode());
			log.info("Request ID:      " + oe.getRequestId());
			log.info("Host ID:           " + oe.getHostId());
		} catch (ClientException ce) {
			log.info("Caught an ClientException, which means the client encountered "
							+ "a serious internal problem while trying to communicate with OSS, "
							+ "such as not being able to access the network.");
			log.info("Error Message: " + ce.getMessage());
		} catch (ParseException e) {
			e.printStackTrace();
		} finally {
			ossClient.shutdown();
		}
		return fileUrl;
	}
}
public class ProperUtils {

	static ResourceBundle bundle = ResourceBundle.getBundle("resource");
	
	public static String getString(String key){
		return bundle.getString(key);
	}
	
}

pom.xml中配置

<!-- 阿里云OSS服务器SDK -->
    <dependency>
      <groupId>com.aliyun.oss</groupId>
      <artifactId>aliyun-sdk-oss</artifactId>
      <version>${aliyun-sdk-oss.version}</version>
    </dependency>
这里提供一个 Java 版本的阿里云 OSS 工具类,方便上传、下载、删除等操作。 ```java import com.aliyun.oss.ClientConfiguration; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.model.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.URL; import java.util.Date; import java.util.List; /** * 阿里云 OSS 工具类 */ public class AliyunOSSUtil { private static final Logger LOGGER = LoggerFactory.getLogger(AliyunOSSUtil.class); private static OSS ossClient; /** * 初始化 OSS 客户端 * * @param endpoint OSS 服务的 endpoint * @param accessKeyId 访问 OSS 服务的 accessKeyId * @param accessKeySecret 访问 OSS 服务的 accessKeySecret */ public static void initOSSClient(String endpoint, String accessKeyId, String accessKeySecret) { ClientConfiguration config = new ClientConfiguration(); config.setConnectionTimeout(5000); // 设置连接超时时间,默认50000毫秒 config.setMaxErrorRetry(3); // 设置请求失败后最大重试次数,默认3次 ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, config); } /** * 销毁 OSS 客户端 */ public static void destroyOSSClient() { if (ossClient != null) { ossClient.shutdown(); } } /** * 上传文件到 OSS * * @param bucketName OSS bucket 名称 * @param filePath 本地文件路径 * @param objectName OSS 上的文件名称 * @return 文件 URL */ public static String uploadFile(String bucketName, String filePath, String objectName) { try { // 创建 PutObjectRequest 对象 PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath)); // 如果需要上传时设置存储类型与访问权限,请参考以下示例代码。 // ObjectMetadata metadata = new ObjectMetadata(); // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString()); // metadata.setObjectAcl(CannedAccessControlList.Private); // putObjectRequest.setMetadata(metadata); // 上传文件 ossClient.putObject(putObjectRequest); // 获取文件 URL Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000); // 设置 URL 过期时间为 1 小时 URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration); LOGGER.info("Upload file to OSS success, object name: {}, URL: {}", objectName, url); return url.toString(); } catch (Exception e) { LOGGER.error("Upload file to OSS failed, object name: {}", objectName, e); return null; } } /** * 下载 OSS 上的文件 * * @param bucketName OSS bucket 名称 * @param objectName OSS 上的文件名称 * @param localPath 本地存储路径 */ public static void downloadFile(String bucketName, String objectName, String localPath) { try { // 下载文件 OSSObject ossObject = ossClient.getObject(bucketName, objectName); InputStream inputStream = ossObject.getObjectContent(); OutputStream outputStream = new FileOutputStream(localPath); byte[] buffer = new byte[1024]; int len; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } outputStream.close(); inputStream.close(); LOGGER.info("Download file from OSS success, object name: {}, local path: {}", objectName, localPath); } catch (Exception e) { LOGGER.error("Download file from OSS failed, object name: {}", objectName, e); } } /** * 判断 OSS 上是否存在指定文件 * * @param bucketName OSS bucket 名称 * @param objectName OSS 上的文件名称 * @return true:存在,false:不存在 */ public static boolean isExist(String bucketName, String objectName) { try { return ossClient.doesObjectExist(bucketName, objectName); } catch (Exception e) { LOGGER.error("Check object exist failed, object name: {}", objectName, e); return false; } } /** * 删除 OSS 上的文件 * * @param bucketName OSS bucket 名称 * @param objectName OSS 上的文件名称 */ public static void deleteFile(String bucketName, String objectName) { try { ossClient.deleteObject(bucketName, objectName); LOGGER.info("Delete file from OSS success, object name: {}", objectName); } catch (Exception e) { LOGGER.error("Delete file from OSS failed, object name: {}", objectName, e); } } /** * 列举 OSS bucket 中的所有文件 * * @param bucketName OSS bucket 名称 * @return 文件列表 */ public static List<OSSObjectSummary> listObjects(String bucketName) { try { ObjectListing objectListing = ossClient.listObjects(bucketName); return objectListing.getObjectSummaries(); } catch (Exception e) { LOGGER.error("List objects failed, bucket name: {}", bucketName, e); return null; } } } ``` 使用方法: ```java // 初始化 OSS 客户端 AliyunOSSUtil.initOSSClient("your endpoint", "your accessKeyId", "your accessKeySecret"); // 上传文件 String fileUrl = AliyunOSSUtil.uploadFile("your bucket name", "your local file path", "your object name"); // 下载文件 AliyunOSSUtil.downloadFile("your bucket name", "your object name", "your local path"); // 判断文件是否存在 boolean isExist = AliyunOSSUtil.isExist("your bucket name", "your object name"); // 删除文件 AliyunOSSUtil.deleteFile("your bucket name", "your object name"); // 列举 bucket 中的所有文件 List<OSSObjectSummary> objectSummaries = AliyunOSSUtil.listObjects("your bucket name"); // 销毁 OSS 客户端 AliyunOSSUtil.destroyOSSClient(); ```
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SuperChen12356

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值