OSSUtil.java 18.6 KB
Newer Older
邓实川 committed
1
package cn.timer.api.utils.aliyun;
yuquan.zhu committed
2 3 4 5 6 7 8

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
邓实川 committed
9
import java.util.ArrayList;
yuquan.zhu committed
10 11 12 13
import java.util.Date;
import java.util.Iterator;
import java.util.List;

14 15
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
yuquan.zhu committed
16 17 18 19 20 21
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
邓实川 committed
22 23
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
yuquan.zhu committed
24
import com.aliyun.oss.model.GetObjectRequest;
邓实川 committed
25
import com.aliyun.oss.model.ListObjectsRequest;
yuquan.zhu committed
26
import com.aliyun.oss.model.OSSObject;
邓实川 committed
27 28
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
yuquan.zhu committed
29 30
import com.aliyun.oss.model.PutObjectRequest;

31 32
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
yuquan.zhu committed
33
import cn.hutool.core.util.StrUtil;
邓实川 committed
34 35
import cn.timer.api.utils.Result;
import cn.timer.api.utils.ResultUtil;
yuquan.zhu committed
36 37 38 39 40 41 42

/**
 * OSS接口操作示例 1.创建空间 2.上传文件 3.下载文件
 * 
 * @author dsc
 *
 */
43
@Component
yuquan.zhu committed
44 45
public class OSSUtil {

邓实川 committed
46
	@Value("${config-8timer.Aliyun.endpoint}")
47 48 49 50
	private String endpoint;

	@Value("${config-8timer.Aliyun.ACCESSKEY_ID}")
	private String accessKeyId;
邓实川 committed
51

52 53
	@Value("${config-8timer.Aliyun.SECRET}")
	private String accessKeySecret;
邓实川 committed
54

55 56
	@Value("${config-8timer.Aliyun.bucketName}")
	private String bucketName;
邓实川 committed
57

58 59
	@Value("${config-8timer.Aliyun.bucketName_pri}")
	private String bucketName_pri;
邓实川 committed
60

61 62
	@Value("${config-8timer.Aliyun.project_package}")
	private String project_package;
邓实川 committed
63

64 65
	@Value("${config-8timer.Aliyun.expirationTime}")
	private String expirationTime;
邓实川 committed
66

67 68 69
	@Value("${config-8timer.Aliyun.expirationTime_pri}")
	private String expirationTime_pri;

yuquan.zhu committed
70 71
	/**
	 * 1.创建储存空间 sout控制台輸出 储存空间名
72
	 * 
yuquan.zhu committed
73 74 75
	 * @param bucketName OSS空间名
	 * @return 成功信息
	 */
76
	public Result<Void> createZone(String bucketName) {
yuquan.zhu committed
77 78 79 80
		// Endpoint以杭州为例,其它Region请按实际情况填写。
		// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录
		// https://ram.console.aliyun.com 创建RAM账号。
		// 创建OSSClient实例。
邓实川 committed
81

yuquan.zhu committed
82 83 84 85 86 87 88 89 90 91 92 93 94
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
		// 创建存储空间。
		ossClient.createBucket(bucketName);
		// 关闭OSSClient。
		ossClient.shutdown();
		// 控制台输出空间名
		System.err.println("bucketName:" + bucketName);
		// 返回成功
		return ResultUtil.success("创建OSS空间成功");
	}

	/**
	 * 2.上传文件到8time-v2
95
	 * 
yuquan.zhu committed
96
	 * @param path 上传路径(用'/'分包)
97
	 * @param ins  输入流
yuquan.zhu committed
98 99
	 * @return
	 */
100
	public String uploadFile(String path, InputStream ins) {
yuquan.zhu committed
101 102 103
		// <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg。
		// String objectName = "8time-v2/test/123.jpg";
		// 创建OSSClient实例。
邓实川 committed
104 105 106
		System.err.println(endpoint);
		System.err.println(accessKeyId);
		System.err.println(accessKeySecret);
yuquan.zhu committed
107 108 109 110
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

		// 创建PutObjectRequest对象。
		// 项目名+用户公司id+模块名+文件夹名+文件名
111 112
		PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, path, ins);
		// [file1,file2,file3],["mk1/img","mk1"]
yuquan.zhu committed
113 114 115 116 117 118 119 120 121 122
		// 如果需要上传时设置存储类型与访问权限,请参考以下示例代码。
		// ObjectMetadata metadata = new ObjectMetadata();
		// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS,
		// StorageClass.Standard.toString());
		// metadata.setObjectAcl(CannedAccessControlList.Private);
		// putObjectRequest.setMetadata(metadata);

		// 上传文件。
		ossClient.putObject(putObjectRequest);

123
		// 设置URL过期时间为100年。 1s 1h 1d 1y 100y
124 125 126
//		Date expiration = new Date(new Date().getTime() + 1000L * 3600 * 24 * 365 * 100);
		Date now = new Date();
		Date expiration = DateUtil.offset(now, DateField.YEAR, 100); // 一百年之后过期
yuquan.zhu committed
127
		// 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
128
		URL url = ossClient.generatePresignedUrl(bucketName, path, expiration);
yuquan.zhu committed
129
		System.err.println(url);
130

yuquan.zhu committed
131 132 133 134 135
		// 关闭OSSClient。
		ossClient.shutdown();
		// 返回上传成功的文件名
		return url.toString();
	}
136

yuquan.zhu committed
137 138
	/**
	 * 3.上传文件到8time-v2-private
139
	 * 
yuquan.zhu committed
140
	 * @param path 上传路径(用'/'分包)
141
	 * @param ins  输入流
yuquan.zhu committed
142 143
	 * @return 文件路径
	 */
144
	public String uploadPrivateFile(String path, InputStream ins) {
yuquan.zhu committed
145 146 147 148 149 150 151
		// <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg。
		// String objectName = "8time-v2/test/123.jpg";
		// 创建OSSClient实例。
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

		// 创建PutObjectRequest对象。
		// 项目名+用户公司id+模块名+文件夹名+文件名
152 153
		PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName_pri, path, ins);
		// [file1,file2,file3],["mk1/img","mk1"]
yuquan.zhu committed
154 155 156 157 158 159 160 161 162 163 164 165 166
		// 如果需要上传时设置存储类型与访问权限,请参考以下示例代码。
		// ObjectMetadata metadata = new ObjectMetadata();
		// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS,
		// StorageClass.Standard.toString());
		// metadata.setObjectAcl(CannedAccessControlList.Private);
		// putObjectRequest.setMetadata(metadata);

		// 上传文件。
		ossClient.putObject(putObjectRequest);

		// 设置URL过期时间为10分钟
		Date expiration = new Date(new Date().getTime() + 1000 * 600);
		// 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
167
		URL url = ossClient.generatePresignedUrl(bucketName_pri, path, expiration);
yuquan.zhu committed
168
		System.err.println(url);
169

yuquan.zhu committed
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
		// 关闭OSSClient。
		ossClient.shutdown();
		// 返回上传成功的文件名
		return path;
	}

	/**
	 * 4.从OSS下载文件
	 * 
	 * @param objectName 完整路径的文件名
	 * @param path       本地储存文件路径
	 * @param orgCode    公司id
	 * @param dir        包名
	 * @param fileName   文件名
	 * @param moudle     模块名
	 * @return 完整文件名
	 */
187
	public Result<String> downloadFile(String orgCode, String moudle, String dir, String fileName, String path) {
yuquan.zhu committed
188 189 190 191 192 193 194
		// <yourObjectName>从OSS下载文件时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg。
		// String objectName = "8time-v2/test/123.jpg";
		// 创建OSSClient实例。
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

		// 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。
		ossClient.getObject(
195
				new GetObjectRequest(bucketName, project_package + orgCode + "/" + moudle + "/" + dir + "/" + fileName),
yuquan.zhu committed
196 197 198 199 200
				new File(path + fileName));

		// 关闭OSSClient。
		ossClient.shutdown();
		// 完整路径的文件名
201
		System.err.println("objectName:" + project_package + orgCode + "/" + moudle + "/" + dir + "/" + fileName);
yuquan.zhu committed
202 203 204 205 206
		System.err.println("path:" + path + fileName);
		// 返回成功的本地路径
		return ResultUtil.success(path + fileName);
	}

207
	public Result<BufferedReader> downloadFile(String objectName) throws IOException {
yuquan.zhu committed
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
		// 创建OSSClient实例。
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

		// ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
		OSSObject ossObject = ossClient.getObject(bucketName, objectName);

		// 读取文件内容。
		System.out.println("Object content:");
		BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));
		while (true) {
			String line = reader.readLine();
			if (line == null)
				break;

			System.out.println("\n" + line);
		}
		// 数据读取完成后,获取的流必须关闭,否则会造成连接泄漏,导致请求无连接可用,程序无法正常工作。
		reader.close();

		// 关闭OSSClient。
		ossClient.shutdown();
		return ResultUtil.data(reader, "下载成功");
	}

	/**
	 * 文件输入流批量上传
	 * 
	 * @param userBean 获取参数
	 * @param files    批量文件
	 * @return 返回上传成功或失败的信息
	 */
239 240 241
	public String uploadFile(MultipartHttpServletRequest request, List<MultipartFile> files) {

		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
yuquan.zhu committed
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256

		String newFileName = null;
		URL url = null;
		try {
			// 上传文件
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			// 判断 request 是否有文件上传,即多部分请求
			if (multipartResolver.isMultipart(request)) {
				// 转换成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 取得request中的所有文件名
				Iterator<String> iter = multiRequest.getFileNames();
				// 此处上传单个文件,如需多个文件改为while循环
				while (iter.hasNext()) {
257

yuquan.zhu committed
258 259 260 261 262
					// 取得上传文件
					files = multiRequest.getFiles(iter.next());
					if (files != null) {
						// 取得当前上传文件的文件名称
						String myFileName = null;
263

yuquan.zhu committed
264 265 266 267 268 269 270 271
						for (MultipartFile file : files) {
							myFileName = file.getOriginalFilename();

							// 如果名称不为“”,说明该文件存在,否则说明该文件不存在
							if (StrUtil.isNotEmpty(myFileName.trim())) {
								newFileName = System.currentTimeMillis()
										+ myFileName.substring(myFileName.lastIndexOf("."));
								// 上传客户端文件到oss,如直接上传服务器文件到oss,可使用new FileInputStream( new File("服务器文件路径"))
272
								ossClient.putObject(bucketName, newFileName, file.getInputStream());
yuquan.zhu committed
273
								// 设置URL过期时间为100年。 1s 1h 1d 1y 100y
274
								Date expiration = new Date(new Date().getTime() + Long.parseLong(expirationTime));
yuquan.zhu committed
275
								// 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
276
								url = ossClient.generatePresignedUrl(bucketName, newFileName, expiration);
yuquan.zhu committed
277 278
								System.err.println(url);
							}
279

yuquan.zhu committed
280
						}
281

yuquan.zhu committed
282 283 284 285 286 287 288 289 290 291 292
					}
				}
			}
		} catch (IOException e) {
			e.getStackTrace();
		} finally {
			// 关闭ossClient
			if (null != ossClient)
				ossClient.shutdown();
		}
		return url.toString();
293

yuquan.zhu committed
294 295 296 297 298 299 300 301 302 303 304
		/*
		 * if (file == null || file.getSize() <= 0) { return
		 * ResultUtil.error("上传的文件为空,请重新选择!"); } else { try {
		 * OSSUtil.uploadFile(userBean.getOrgCode(), className,
		 * file.getOriginalFilename(), file.getInputStream()); } catch (IOException e) {
		 * e.printStackTrace(); } return ResultUtil.success("上传成功"); }
		 */
	}

	/**
	 * 获取8time-v2文件的url
305
	 * 
yuquan.zhu committed
306 307
	 * @return url地址
	 */
308
	public String getUrl(String path) {
yuquan.zhu committed
309 310 311
		// 创建OSSClient实例。
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

312 313
		// 设置URL过期时间为100年。 1s 1h 1d 1y 10y
		Date expiration = new Date(new Date().getTime() + Long.parseLong(expirationTime));
yuquan.zhu committed
314
		// 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
315
		URL url = ossClient.generatePresignedUrl(bucketName, path, expiration);
yuquan.zhu committed
316 317 318 319 320 321 322 323
		System.err.println(url);
		// 关闭OSSClient。
		ossClient.shutdown();
		return url.toString();
	}

	/**
	 * 获取8time-v2-private文件的url
324
	 * 
yuquan.zhu committed
325 326
	 * @return url地址
	 */
327
	public String getUrlP(String path) {
yuquan.zhu committed
328 329 330
		// 创建OSSClient实例。
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

331 332
		// 设置URL过期时间为10分钟。
		Date expiration = new Date(new Date().getTime() + Long.parseLong(expirationTime_pri));
yuquan.zhu committed
333
		// 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
334
		URL url = ossClient.generatePresignedUrl(bucketName, path, expiration);
yuquan.zhu committed
335 336 337 338 339
		System.err.println(url);
		// 关闭OSSClient。
		ossClient.shutdown();
		return url.toString();
	}
340

邓实川 committed
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
	/**
	 * 删除单个
	 * 
	 * @param objectName 文件名
	 */
	public void delSingleFile(String objectName) {
//		// Endpoint以杭州为例,其它Region请按实际情况填写。
//		String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
//		// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
//		String accessKeyId = "<yourAccessKeyId>";
//		String accessKeySecret = "<yourAccessKeySecret>";
//		String bucketName = "<yourBucketName>";
//		String objectName = "<yourObjectName>";

		// 创建OSSClient实例。
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

		// 删除文件。如需删除文件夹,请将ObjectName设置为对应的文件夹名称。如果文件夹非空,则需要将文件夹下的所有object删除后才能删除该文件夹。
		ossClient.deleteObject(bucketName, objectName);

		// 关闭OSSClient。
		ossClient.shutdown();
	}

	/**
	 * 删除多个文件
367 368
	 * 
	 * @param keys  需要删除的文件。
邓实川 committed
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
	 * @param quiet 返回模式。true表示简单模式,false表示详细模式。默认为详细模式。
	 * @return 删除结果。详细模式下为删除成功的文件列表,简单模式下为删除失败的文件列表。
	 */
	public List<String> delFiles(List<String> keys, boolean quiet) {
//		// Endpoint以杭州为例,其它Region请按实际情况填写。
//		String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
//		// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
//		String accessKeyId = "<yourAccessKeyId>";
//		String accessKeySecret = "<yourAccessKeySecret>";
//		String bucketName = "<yourBucketName>";

		// 创建OSSClient实例。
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

		// 删除文件。key等同于ObjectName,表示删除OSS文件时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg。
//		List<String> keys = new ArrayList<String>();
//		keys.add("key0");
//		keys.add("key1");
//		keys.add("key2");

		DeleteObjectsResult deleteObjectsResult = ossClient
				.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(keys).withQuiet(quiet));
		List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();

		// 关闭OSSClient。
		ossClient.shutdown();

		return deletedObjects;
	}

	/**
	 * 删除指定前缀(prefix)的文件
401
	 * 
邓实川 committed
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
	 * @param prefix
	 */
	public void delPrefixWith(String prefix) {
//		// Endpoint以杭州为例,其它Region请按实际情况填写。
//		String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
//		// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录
//		// https://ram.console.aliyun.com 创建RAM账号。
//		String accessKeyId = "<yourAccessKeyId>";
//		String accessKeySecret = "<yourAccessKeySecret>";
//		String bucketName = "<yourBucketName>";
//
//		// 指定前缀。
//		final String prefix = "<yourkeyPrefix>";

		// 创建OSSClient实例。
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

		// 列举所有包含指定前缀的文件并删除。
		String nextMarker = null;
		ObjectListing objectListing = null;
		do {
			ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName).withPrefix(prefix)
					.withMarker(nextMarker);

			objectListing = ossClient.listObjects(listObjectsRequest);
			if (objectListing.getObjectSummaries().size() > 0) {
				List<String> keys = new ArrayList<String>();
				for (OSSObjectSummary s : objectListing.getObjectSummaries()) {
					System.out.println("key name: " + s.getKey());
					keys.add(s.getKey());
				}
				DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucketName).withKeys(keys);
				ossClient.deleteObjects(deleteObjectsRequest);
			}

			nextMarker = objectListing.getNextMarker();
		} while (objectListing.isTruncated());

		// 关闭OSSClient。
		ossClient.shutdown();
	}
443

yuquan.zhu committed
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
	/*
	 * (跨域资源) // Endpoint以杭州为例,其它Region请按实际情况填写。 String endpoint =
	 * "http://oss-cn-hangzhou.aliyuncs.com"; //
	 * 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录
	 * https://ram.console.aliyun.com 创建RAM账号 String accessKeyId =
	 * "<yourAccessKeyId>"; String accessKeySecret = "<yourAccessKeySecret>"; String
	 * bucketName = "<yourBucketName>";
	 * 
	 * // 创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(endpoint,
	 * accessKeyId, accessKeySecret);
	 * 
	 * SetBucketCORSRequest request = new SetBucketCORSRequest(bucketName);
	 * 
	 * // 跨域资源共享规则的容器,每个存储空间最多允许10条规则。 ArrayList<CORSRule> putCorsRules = new
	 * ArrayList<CORSRule>();
	 * 
	 * CORSRule corRule = new CORSRule();
	 * 
	 * ArrayList<String> allowedOrigin = new ArrayList<String>(); // 指定允许跨域请求的来源。
	 * allowedOrigin.add( "http://www.b.com");
	 * 
	 * ArrayList<String> allowedMethod = new ArrayList<String>(); //
	 * 指定允许的跨域请求方法(GET/PUT/DELETE/POST/HEAD)。 allowedMethod.add("GET");
	 * 
	 * ArrayList<String> allowedHeader = new ArrayList<String>(); //
	 * 是否允许预取指令(OPTIONS)中Access-Control-Request-Headers头中指定的Header。
	 * allowedHeader.add("x-oss-test");
	 * 
	 * ArrayList<String> exposedHeader = new ArrayList<String>(); //
	 * 指定允许用户从应用程序中访问的响应头。 exposedHeader.add("x-oss-test1"); //
	 * AllowedOrigins和AllowedMethods最多支持一个星号(*)通配符。星号(*)表示允许所有的域来源或者操作。
	 * corRule.setAllowedMethods(allowedMethod);
	 * corRule.setAllowedOrigins(allowedOrigin); //
	 * AllowedHeaders和ExposeHeaders不支持通配符。 corRule.setAllowedHeaders(allowedHeader);
	 * corRule.setExposeHeaders(exposedHeader); //
	 * 指定浏览器对特定资源的预取(OPTIONS)请求返回结果的缓存时间,单位为秒。 corRule.setMaxAgeSeconds(10);
	 * 
	 * // 最多允许10条规则。 putCorsRules.add(corRule); // 已存在的规则将被覆盖。
	 * request.setCorsRules(putCorsRules); ossClient.setBucketCORS(request);
	 * 
	 * // 关闭OSSClient。 ossClient.shutdown();
	 */

}