概述
笔者也不知道该怎么概述,在下面代码中主要就是几个参数比较难以搞懂,搞懂了参数就不难使用。那么开始吧!
Maven地址
<dependency >
<groupId > com.aliyun.oss</groupId >
<artifactId > aliyun-sdk-oss</artifactId >
<version > 3.16.1</version >
</dependency >
<dependency >
<groupId > javax.xml.bind</groupId >
<artifactId > jaxb-api</artifactId >
<version > 2.3.1</version >
</dependency >
<dependency >
<groupId > javax.activation</groupId >
<artifactId > activation</artifactId >
<version > 1.1.1</version >
</dependency >
<dependency >
<groupId > org.glassfish.jaxb</groupId >
<artifactId > jaxb-runtime</artifactId >
<version > 2.3.3</version >
</dependency >
必要参数
accessKeyId
accessKeyId 是在登录阿里云官网时需要创建的,谁交给你这个开发任务那么就问谁去要。假设对方不知道,就要问对方要购买阿里云OSS服务的账号密码,然后在去控制台 查看,具体查看方法可以百度。
accessKeySecret
accessKeySecret 也是在登录阿里云官网时需要创建的,获取方法同上!
bucket
Bucket 是在购买 OSS 服务的后要创建的,在哪里创建自行百度。
endPoint
endPoint 是在购买 OSS 服务的后要创建的,在哪里创建自行百度。在下面图片的两个标记中,在点击确定按钮之前需要把这个两个参数保存好,虽然后期也可以查看,但是比较麻烦。
OSS配置类
笔者是把以上参数配置在 Springboot 的 yml 配置文件中,记得在保存的endPoint前加上https 。以下配置仅供参考
aliyunoss:
accessKeyId: LTAI5t8LBSMKX2R8ZLtn****
accessKeySecret: ekwm3JDe9wUbzuPLA8MF5f8tmT****
bucket: blog****pig
endPoint: https://oss-cn-beijing.aliyuncs.com
@Data
@Configuration
@ConfigurationProperties(prefix = "aliyunoss")
public class ALiYunOSSProperties {
private String accessKeyId;
private String accessKeySecret;
private String bucket;
private String endPoint;
}
具体实现代码
顶级接口
public interface BlogFileService {
String uploadPictureFile (MultipartFile file) throws ClientException, IOException;
InputStream downloadPictureFile (String uri, HttpServletRequest request, HttpServletResponse response) ;
void deletePictureFile (String url) ;
}
OSS实现类
@Slf4j
@Service
public class AliYunOSSFileImpl implements BlogFileService {
@Value("aliyunoss.accessKeyId")
private String accessKeyId;
@Value("aliyunoss.accessKeySecret")
private String accessKeySecret;
@Value("aliyunoss.bucket")
private String bucket;
@Value("aliyunoss.endPoint")
private String endPoint;
@Autowired
private ALiYunOSSProperties aLiYunOSSProperties;
@Override
public String uploadPictureFile (MultipartFile file) {
String originalFilename = file.getOriginalFilename();
String accessKeyId = aLiYunOSSProperties.getAccessKeyId();
String accessKeySecret = aLiYunOSSProperties.getAccessKeySecret();
String endPoint = aLiYunOSSProperties.getEndPoint();
String bucket = aLiYunOSSProperties.getBucket();
CredentialsProvider credentialsProviderCode = new DefaultCredentialProvider (accessKeyId, accessKeySecret);
OSS ossClient = new OSSClientBuilder ().build(endPoint, credentialsProviderCode);
try {
ossClient.putObject(bucket, originalFilename, new ByteArrayInputStream (file.getBytes()));
Date expiration = new Date (System.currentTimeMillis() + 3600 * 24 * 365 * 15 * 1000L );
return ossClient.generatePresignedUrl(bucket, originalFilename, expiration).toString();
} catch (OSSException oe) {
log.error("Caught an OSSException, which means your request made it to OSS, but was rejected with an error response for some reason." );
log.error("Error Message:" + oe.getErrorMessage());
log.error("Error Code:" + oe.getErrorCode());
log.error("Request ID:" + oe.getRequestId());
log.error("Host ID:" + oe.getHostId());
throw new BlogRuntimeException (ResultCode.PHOTO_UPLOAD_FAILED, oe.getMessage());
} catch (com.aliyun.oss.ClientException ce) {
log.error("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.error("Error Message:" + ce.getMessage());
throw new BlogRuntimeException (ResultCode.PHOTO_UPLOAD_FAILED, ce.getMessage());
}catch (IOException ioException){
throw new BlogRuntimeException (ResultCode.PHOTO_UPLOAD_FAILED, ioException.getMessage());
} finally {
ossClient.shutdown();
}
}
@Override
public InputStream downloadPictureFile (String url, HttpServletRequest request, HttpServletResponse response) {
String accessKeyId = aLiYunOSSProperties.getAccessKeyId();
String accessKeySecret = aLiYunOSSProperties.getAccessKeySecret();
String endPoint = aLiYunOSSProperties.getEndPoint();
String bucket = aLiYunOSSProperties.getBucket();
CredentialsProvider credentialsProviderCode = new DefaultCredentialProvider (accessKeyId, accessKeySecret);
OSS ossClient = new OSSClientBuilder ().build(endPoint, credentialsProviderCode);
String fileName = url.substring(url.indexOf("/" , 8 ) + 1 , url.indexOf("?" ));
try {
OSSObject ossObject = ossClient.getObject(new GetObjectRequest (bucket, fileName));
InputStream objectContent = ossObject.getObjectContent();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream ();
byte [] buffer = new byte [1024 ];
int len;
while ((len = objectContent.read(buffer)) > -1 ) {
outputStream.write(buffer, 0 , len);
}
outputStream.flush();
outputStream.close();
objectContent.close();
return new ByteArrayInputStream (outputStream.toByteArray());
} catch (OSSException oe) {
log.error("Caught an OSSException, which means your request made it to OSS, but was rejected with an error response for some reason." );
log.error("Error Message:" + oe.getErrorMessage());
log.error("Error Code:" + oe.getErrorCode());
log.error("Request ID:" + oe.getRequestId());
log.error("Host ID:" + oe.getHostId());
throw new BlogRuntimeException (ResultCode.FILE_DOES_NOT_EXIST);
} catch (ClientException ce) {
log.error("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.error("Error Message:" + ce.getMessage());
throw new BlogRuntimeException (ResultCode.FILE_DOES_NOT_EXIST);
} catch (IOException e) {
log.error("AliYunOssServiceImpl downloadFile" , e);
throw new BlogRuntimeException (ResultCode.FILE_DOES_NOT_EXIST);
} finally {
if (ossClient != null ) {
ossClient.shutdown();
}
}
}
@Override
public void deletePictureFile (String url) {
String accessKeyId = aLiYunOSSProperties.getAccessKeyId();
String accessKeySecret = aLiYunOSSProperties.getAccessKeySecret();
String endPoint = aLiYunOSSProperties.getEndPoint();
String bucket = aLiYunOSSProperties.getBucket();
CredentialsProvider credentialsProviderCode = new DefaultCredentialProvider (accessKeyId, accessKeySecret);
OSS ossClient = new OSSClientBuilder ().build(endPoint, credentialsProviderCode);
String fileName = url.substring(url.indexOf("/" , 8 ) + 1 , url.indexOf("?" ));
ossClient.deleteObject(bucket, fileName);
ossClient.shutdown();
}
}
Controller层
@Slf4j
@RestController
@RequestMapping("/blog/version-1.0/file")
public class FileController {
@Autowired
private BlogFileService aLiYunOSSFile;
@PostMapping("/uploadPicture")
public Result<String> uploadPicture (MultipartFile file) throws ClientException, IOException {
log.info("FileController uploadPicture Request param: {}" , file);
String picture = aLiYunOSSFile.uploadPictureFile(file);
log.info("FileController uploadPicture Response PictureURL: {}" , picture);
return ResultBuilder.successResult(picture);
}
@DeleteMapping("/deletePicture")
public Result<String> deletePicture (@RequestParam String url) {
log.info("FileController uploadPicture Request param: {}" , url);
aLiYunOSSFile.deletePictureFile(url);
return ResultBuilder.successResult();
}
@GetMapping(value = "/downloadPicture", produces = {MediaType.APPLICATION_OCTET_STREAM_VALUE, MediaType.APPLICATION_JSON_VALUE})
public Result<String> downloadPicture (@RequestParam String url, HttpServletRequest request, HttpServletResponse response) {
log.info("FileController downloadPicture Request param: {}" , url);
InputStream inputStream = null ;
BufferedOutputStream outputStream = null ;
String fileName = url.substring(url.indexOf("/" , 8 ) + 1 , url.indexOf("?" ));
try {
inputStream = aLiYunOSSFile.downloadPictureFile(url, request, response);
response.reset();
response.setHeader("Content-disposition" , "attachment;filename=" + setFileDownloadHeader(request, fileName));
response.setContentType("application/octet-stream;charset=UTF-8" );
outputStream = new BufferedOutputStream (response.getOutputStream());
if (inputStream != null ) {
int len;
while ((len = inputStream.read()) != -1 ) {
outputStream.write(len);
outputStream.flush();
}
}
} catch (Exception e) {
log.error("FileController downloadFile error" , e);
} finally {
if (Objects.nonNull(inputStream)) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (Objects.nonNull(outputStream)) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return ResultBuilder.successResult();
}
public static String setFileDownloadHeader (HttpServletRequest request, String fileName) throws UnsupportedEncodingException {
final String agent = request.getHeader("USER-AGENT" );
String filename = fileName;
if (agent.contains("MSIE" )) {
filename = URLEncoder.encode(filename, StandardCharsets.UTF_8);
filename = filename.replace("+" , " " );
} else if (agent.contains("Firefox" )) {
filename = new String (fileName.getBytes(), "ISO8859-1" );
} else if (agent.contains("Chrome" )) {
filename = URLEncoder.encode(filename, StandardCharsets.UTF_8);
} else {
filename = URLEncoder.encode(filename, StandardCharsets.UTF_8);
}
return filename;
}
}
Tips
对读者的一些小建议
读者任务时间不紧迫,请结合官网文档 进行查看和Debug本代码。
时间紧迫,请直接粘贴复制即用。
还有什么问题可以给笔者发邮件,599303650@qq.com
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)