Java SpringBoot 教程:使用阿里云OSS实现通用文件上传接口
文件上传接口应该作为通用的API接口,附上时序图。文件上传接口是Web开发中常见的功能之一,通过该接口可以实现将文件上传至服务器并进一步存储到云存储服务中。本文将介绍如何实现一个通用的文件上传接口,并提供后端代码示例。
·
文件上传接口实现
文件上传接口应该作为通用的API接口,附上时序图
后端实现
后端实现参考:如何使用OSS Java SDK完成常见操作_对象存储(OSS)-阿里云帮助中心 (aliyun.com)
环境配置: 参考安装OSS Java SDK_对象存储(OSS)-阿里云帮助中心 (aliyun.com)
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</dependency>
1.创建阿里云oss属性配置类
/**
* 阿里云oss的配置属性类
*/
@Component
@ConfigurationProperties(prefix = "sky.alioss")
@Data
public class AliOssProperties {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
}
2.application.yml配置
3.实现阿里云 OSS 工具类
@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
/**
* 文件上传
*
* @param bytes
* @param objectName
* @return
*/
public String upload(byte[] bytes, String objectName) {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("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.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
//文件访问路径规则 https://BucketName.Endpoint/ObjectName
StringBuilder stringBuilder = new StringBuilder("https://");
stringBuilder
.append(bucketName)
.append(".")
.append(endpoint)
.append("/")
.append(objectName);
log.info("文件上传到:{}", stringBuilder.toString());
return stringBuilder.toString();
}
}
4.通过配置类配置工具类的属性
/**
* AliOssUtil属性的配置类
*/
@Configuration
@Slf4j
public class AliOSSConfiguration {
@Bean
// 当你的bean被注册之后,如果注册相同类型的bean,就不会成功,它会保证你的bean只有一个,即你的实例只有一个。
// 如果不加@ConditionalOnMissingBean,当你注册多个相同的bean时,会出现异常,以此来告诉开发人员。
@ConditionalOnMissingBean
public AliOssUtil aliOssUtil(AliOssProperties aliOssProperties) {
log.info("阿里云OSS实例化");
return new AliOssUtil(aliOssProperties.getEndpoint(),
aliOssProperties.getAccessKeyId(),
aliOssProperties.getAccessKeySecret(),
aliOssProperties.getBucketName());
}
}
5.实现上传文件的通用接口
文件上传至服务器后再上传至阿里云
@RestController
@RequestMapping("/admin/common")
@Slf4j
@Api(tags = "通用接口")
public class CommonController {
@Autowired
private AliOssUtil aliOssUtil;
@PostMapping("/upload")
@ApiOperation("文件上传")
public Result<String> uploadFile(MultipartFile file) {
// 获取原始文件名
String originalFilename = file.getOriginalFilename();
// 截取最后一个.xxx
String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
// 拼接时间日期
LocalDateTime now = LocalDateTime.now();
String format = now.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
// 生成UUID 拼接后缀,避免重名问题
String objectName = format + "/" + UUID.randomUUID().toString() + suffixName;
try {
// 返回文件上传路径
String uploadedPath = aliOssUtil.upload(file.getBytes(), objectName);
return Result.success(uploadedPath);
} catch (IOException e) {
log.info("文件上传失败:{}", e);
throw new RuntimeException(e);
}
}
}
前端测试
你可以使用工具如 Postman、ApiFox 或前端组件上传等方式来测试文件上传接口的功能。
阿里云OSS控制台目录结构
在阿里云控制台中,你可以创建对应的存储空间(Bucket),并按照指定的目录结构查看和修改存储上传的文件。
立下Flag
最近我有时间一定把前端直传OSS的博客给写了!
更多推荐
所有评论(0)