Bootstrap

阿里云OSS在Java中的使用

需要先在阿里云中开启OSS服务,并购买相应的资源包

这里是具体实现的逻辑

/**
 * @author MoDianBai
 * @date 2023/03/22 15:36
 **/
 
import cn.hutool.core.lang.UUID;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.mss.annotation.rest.AnonymousPostMapping;
import com.mss.base.ResponseWrapper;
import com.mss.exception.BadRequestException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import static com.mss.base.ResponseCode.SUCCESS;


@RequestMapping("/ossFile")
public class OssFileController {


	/**
	 * 我自己抽的统一文件前缀
	 */
	private final String prefix = "前缀字符串";
	/**
	 * bucket
	 */
	private final String bucket = "bucket";
	/**
	 * 你的 bucket 外网访问域名
	 */
	private final String endpoint = "访问域名";
	/**
	 * 访问路径
	 */
	private final String bucketHost = "路径";
	/**
	 * Key&&Secret
	 */
	private final String accessKeyId = "Key";
	private final String accessKeySecret = "Secret";
	/**
	 * 生成文件路径
	 */
	private final SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");



	/**
	 * 单个文件上传
	 *
	 * @param file
	 *
	 * @return
	 */
	@AnonymousPostMapping("/upload")
	@ApiOperation(value = "单个文件上传", notes = "单个文件上传")
	public ResponseWrapper<String> upload(MultipartFile file) {
		// 路径拼接
		String dataPath = format.format(new Date());
		// 文件名称生成
		String uuid = UUID.randomUUID().toString().replace("-", "");
		String path = prefix + "/" + dataPath + "/" + uuid + file.getOriginalFilename();
		try {
			// 上传
			ossUpload(bucket, path, file.getInputStream());
		} catch (IOException e) {
			throw new BadRequestException("文件上传失败!");
		}
		// 因为 oss 不会返回访问 url 所以我们自己可以拼接一个:
		// 协议(https://) + 域名访问地址(j3-communication.oss-cn-guangzhou.aliyuncs.com) + 自己拼接的路径(xxx/xxx/a.jpg)
		return ResponseWrapper.success("https://" + bucketHost + "/" + path);
	}


	/**
	 * 多个文件上传
	 *
	 * @param files
	 *
	 * @return
	 */
	@PostMapping("/uploads")
	@ApiOperation(value = "多个文件上传", notes = "多个文件上传")
	public ResponseWrapper<List<String>> upload(MultipartFile[] files) {
		List<String> usrList = new ArrayList<>(files.length);
		for(MultipartFile file : files) {
			usrList.add(uploadFile(file));
		}
		return ResponseWrapper.success(usrList);
	}

	private String uploadFile(MultipartFile file) {
		// 路径拼接
		String dataPath = format.format(new Date());
		// 文件名称生成
		String uuid = UUID.randomUUID().toString().replace("-", "");
		String path = prefix + "/" + dataPath + "/" + uuid + file.getOriginalFilename();
		try {
			// 上传
			ossUpload(bucket, path, file.getInputStream());
		} catch (IOException e) {
			throw new BadRequestException("文件上传失败!");
		}
		// 因为 oss 不会返回访问 url 所以我们自己可以拼接一个:
		// 协议(https://) + 域名访问地址(j3-communication.oss-cn-guangzhou.aliyuncs.com) + 自己拼接的路径(xxx/xxx/a.jpg)
		return "https://" + bucketHost + "/" + path;
	}


	/**
	 * 单个删除
	 *
	 * @param url 文件url
	 */
	@PostMapping("/delete")
	@ApiOperation(value = "单个删除", notes = "单个删除")
	public ResponseWrapper delete(@RequestParam("url") String url) {
		// 处理 url
		log.info("============入参:{}", url);
		String path = url.substring(("https://" + bucketHost + "/").length());
		log.info("============path:{}", path);
		ossDelete(bucket, Collections.singletonList(path));

		return ResponseWrapper.success(SUCCESS);
	}

	/**
	 * 多个删除
	 *
	 * @param urlList
	 */
	@PostMapping("/deletes")
	@ApiOperation(value = "多个删除", notes = "多个删除")
	public ResponseWrapper delete(List<String> urlList) {
		List<String> keys = new ArrayList<>(urlList.size());
		for(String url : urlList) {
			keys.add(url.substring(("https://" + bucketHost + "/").length()));
		}
		ossDelete(bucket, keys);

		return ResponseWrapper.success(SUCCESS);
	}




	/**
	 * 具体上传代码
	 *
	 * @param bucket backet名称
	 * @param path 路径
	 * @param inputStream 文件流
	 *
	 * @return
	 */
	private PutObjectResult ossUpload(String bucket, String path, InputStream inputStream) {
		OSS ossClient = null;
		PutObjectResult putObjectResult = null;
		try {
			// 创建OSSClient实例。
			ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
			// 通过文件流的形式上传文件
			putObjectResult = ossClient.putObject(bucket, path, inputStream);
		} catch (Exception e) {
			//错误处理
			log.error("==========ossUpload_error, {}", e);
			throw new BadRequestException("文件上传失败!");
		} finally {
			//资源关闭
			assert ossClient != null;
			ossClient.shutdown();
		}
		return putObjectResult;
	}



	/**
	 * 具体删除代码
	 *
	 * @param bucket backet
	 * @param pathList 文件url列表
	 */
	private void ossDelete(String bucket, List<String> pathList) {
		OSS ossClient = null;
		try {
			// 创建OSSClient实例。
			ossClient = new OSSClientBuilder().build(endpoint
					, accessKeyId
					, accessKeySecret);
			// ossClient.deleteObject(bucket, path);
			DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucket);
			deleteObjectsRequest.setKeys(pathList);
			ossClient.deleteObjects(deleteObjectsRequest);
		} catch (Exception e) {
			//错误处理
			log.error("==========ossUpload_error, {}", e);
			throw new BadRequestException("文件删除失败!");
		} finally {
			//资源关闭
			assert ossClient != null;
			ossClient.shutdown();
		}
	}


}


;