1、在service模块下创建子模块service_oss
2、导入OSS依赖
<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>
3、创建包、controller、service、配置文件
(1)创建包
(2)启动类
@SpringBootApplication
@ComponentScan({"com.atguigu"})
public class OssApplication {
public static void main(String[] args) {
SpringApplication.run(OssApplication.class, args);
}
}
(3)配置文件
#服务端口
server.port=8002
#服务名
spring.application.name=service-oss
#环境设置:dev、test、prod
spring.profiles.active=dev
4、编写上传接口服务controller
@Api(description="上传文件管理")
@RestController
@RequestMapping("/eduoss/fileoss")
@CrossOrigin
public class FileOssController {
@Autowired
private FileService fileService;
@ApiOperation(value = "上传文件")
@PostMapping("fileUpload")
public R fileUploadOss(MultipartFile file){
//1 得到上传文件
//2 上传阿里云OSS
String url = fileService.uploadFileOss(file);
//3 返回OSS地址
return R.ok().data("url",url);
}
}
5、编写service实现(注意:阿里云 OSS,不同的服务器,地址不同,代码中声明部分需要自己填写自己的阿里oss服务器相关信息)
@Service
public class FileServiceImpl implements FileService {
//上传文件阿里云OSS
@Override
public String uploadFileOss(MultipartFile file) {
// Endpoint以杭州为例,其它Region请按实际情况填写。
String endpoint = "此处须填写自己的阿里云OSS服务的endpoint ";
// 云账号AccessKey有所有API访问权限,建议遵循阿里云安全最佳实践,创建并使用RAM子账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建。
String accessKeyId = "此处须填写自己的阿里云OSS服务的accessKeyId ";
String accessKeySecret = "此处须填写自己的阿里云OSS服务的accessKeySecret ";
String bucketName = "此处须填写自己的阿里云OSS服务的bucketName ";
try {
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
//上传文件流
InputStream inputStream = file.getInputStream();
String fileName = file.getOriginalFilename();
ossClient.putObject(bucketName, fileName, inputStream);
// 关闭OSSClient。
ossClient.shutdown();
//拼接url
//https://guli-file200211test.oss-cn-beijing.aliyuncs.com/01.jpg
String url = "https://"+bucketName+"."+endpoint+"/"+fileName;
return url;
} catch (IOException e) {
throw new GuliException(20001,"上传失败");
}
}
}
6、启动工程
出现报下面的错误:
(1)在启动类添加信息,不访问数据库
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@ComponentScan({"com.atguigu"})
public class OssApplication {
public static void main(String[] args) {
SpringApplication.run(OssApplication.class, args);
}
}
7、测试
使用swagger进行测试:http://localhost:8002/swagger-ui.html