1.创建springboot项目,引入下面依赖
<dependencies>
<!--阿里云oss依赖-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
</dependency>
<!--日期工具栏依赖-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
</dependencies>
2.在配置文件添加下面
#服务端口
server.port=8002
#服务名
spring.application.name=service-oss
#环境设置
spring.profiles.active=dev
#阿里云oss
#不同服务器,地址不同
aliyun.oss.file.endpoint=oss-cn-guangzhou.aliyuncs.com
aliyun.oss.file.keyid=LTAI4Fy3GqAXraAVQUd7vxKh
aliyun.oss.file.keysecret=mfDksxa5H0Sa5AeTkQ1Iz3EGa4LSq0
#可以在控制台创建,也可以在java中创建
aliyun.oss.file.bucketname=chan-1010
3.创建常量类,读取配置文件的值
package com.chang.oss.utils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component//spring加载完后,执行这个方法
public class ConstantPropertiesUtils implements InitializingBean {
//读取配置文件的值
@Value("${aliyun.oss.file.endpoint}")
private String endpoint;
@Value("${aliyun.oss.file.keyid}")
private String keyid;
@Value("${aliyun.oss.file.keysecret}")
private String keysecret;
@Value("${aliyun.oss.file.bucketname}")
private String bucketname;
//定义静态公开常量
public static String END_POINT;
public static String KEY_ID;
public static String KEY_SECRET;
public static String BUCKET_NAME;
@Override
public void afterPropertiesSet() throws Exception {
END_POINT=endpoint;
KEY_ID=keyid;
KEY_SECRET=keysecret;
BUCKET_NAME=bucketname;
}
}
3.创建controller层
package com.chang.oss.controller;
import com.chang.commonutils.R;
import com.chang.oss.service.OssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
@CrossOrigin
@RequestMapping("/eduoss/fileoss")
public class OssController {
@Autowired
private OssService ossService;
//上传头像的方法
@PostMapping()
public R uploadOssFile(MultipartFile file){
//返回上传到oss的路径
String url = ossService.uploadFileAvatar(file);
return R.ok().data("url",url);
}
}
4.创建service层并且实现实现类
package com.chang.oss.service;
import org.springframework.web.multipart.MultipartFile;
public interface OssService {
//上传头像到oss
String uploadFileAvatar(MultipartFile file);
}
package com.chang.oss.impl;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.chang.oss.service.OssService;
import com.chang.oss.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import java.util.UUID;
@Service
public class OssServiceImpl implements OssService {
//上传头像到oss
@Override
public String uploadFileAvatar(MultipartFile file) {
// yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
String endpoint = ConstantPropertiesUtils.END_POINT;
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessKeyId = ConstantPropertiesUtils.KEY_ID;
String accessKeySecret = ConstantPropertiesUtils.KEY_SECRET;
String bucketName= ConstantPropertiesUtils.BUCKET_NAME;
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//获取原始文件名称
String filename = file.getOriginalFilename();
//1.文件名称里面添加唯一随机的值
String uuid = UUID.randomUUID().toString().replace("-","");
filename=filename+uuid;
//2.把文件按照日期进行分类
String dataPath = new DateTime().toString("yyyy/MM/dd");
//拼接
filename = dataPath+"/"+filename;
try {
//获取上传文件流
InputStream inputStream = file.getInputStream();
//调用oss方法实现上传
//第一个参数:Bucket名称
//第二个参数:上传到oss文件名称和路径 /aa/bb/1.jpg
//第三个参数:上传文件输入流
ossClient.putObject(bucketName,filename,inputStream);
// 关闭OSSClient。
ossClient.shutdown();
//需要把上传到阿里云oss的路径手动拼接出来
String url = "https://"+bucketName+"."+endpoint+"/"+filename;
return url;
}catch (Exception exception){
exception.printStackTrace();
return null;
}
}
}
5.启动类
package com.chang.oss;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableSwagger2
@ComponentScan("com.atguigu")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}