一.项目需求
1.springboot实现图片阿里云阿里云Oss服务器,实现用户的相关的图片存储到阿里云Oss对象里面存储,下面是直接上代码形式,已经一些相关的说明
2.项目中引入依赖
<!--Oss-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.1.0</version>
</dependency>
3.配置文件中的配置,我这里是配置yml的形式的
4.代码逻辑有点简单,所有就直接全部写在了控制层,见谅
/**
* 上传图片到阿里云
*
* @author Gin
*/
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/api/student/oss")
public class OssController {
private final OssService ossService;
@Value("${aliyun.oss.file.keyid}")
private String accessKeyId;
@Value("${aliyun.oss.file.endpoint}")
private String endPoint;
@Value("${aliyun.oss.file.keysecret}")
private String accessKeySecret;
@Value("${aliyun.oss.file.bucketname}")
private String bucketName;
/**
* 上传图片阿里云Oss服务器
*/
@PostMapping("/upload/{type}")
public RestResponse uploadPhoto(@PathVariable String type, MultipartFile file) throws IOException {
// 创建OSSClient实例
OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
// 获取上传文件流。
InputStream inputStream = file.getInputStream();
// 获取文件名称
String fileName = file.getOriginalFilename();
if (ObjectUtil.isNull(fileName)) {
return RestResponse.fail(SystemCode.ParameterValidError.getCode(), "文件名称错误");
}
String uuid = UUID.randomUUID().toString().replace("-", "");
fileName = (uuid + fileName.substring(fileName.lastIndexOf(".")));
String ossFile = "";
String filePath = "";
switch (type) {
// 照片
case "photo":
ossFile = "photo";
filePath = "photo" + "/" + fileName;
break;
// 体检表
case "physical":
ossFile = "physical_examination";
filePath = "physical_examination" + "/" + fileName;
break;
// 审批表
case "approval":
ossFile = "approval";
filePath = "approval" + "/" + fileName;
break;
default:
return RestResponse.fail(SystemCode.ParameterValidError.getCode(), "未知类型");
}
ObjectMetadata meta = new ObjectMetadata();
meta.setContentType("image/jpg");
// 调用OSS方法实现上传
ossClient.putObject(bucketName, filePath, inputStream, meta);
// 关闭OSSClient。
ossClient.shutdown();
return RestResponse.ok("https://" + bucketName + "." + endPoint + "/" + ossFile + "/" + fileName);
}
}
5.我这里是上传三个不同的文件夹,所有返回的路径是动态获取的,还有下面有个地方要注意一下,阿里云默认上传的图片不是在线查看的,记得修改一下