在线教育项目-阿里云对象存储OSS的使用

官方网址及简介

对象存储 OSS

简介:海量、安全、低成本、高可靠的云存储服务,提供99.9999999999%的数据可靠性。使用RESTful API 可以在互联网任何位置存储和访问,容量和处理能力弹性扩展,多种存储类型供选择全面优化存储成本。

开通“对象存储OSS”服务
  • 申请阿里云账号
  • 实名认证
  • 开通“对象存储OSS”服务
  • 进入管理控制台
创建Bucket

流量不多,基本白嫖。我这里选择的是低频访问存储,公共读,区域可以选择离自己近的,其他的都没有开通。
在这里插入图片描述在这里插入图片描述进入该Bucket,大概这个样子,文件管理区域应该是空的。
在这里插入图片描述

Maven项目的依赖

pom.xml

<dependencies>
    <!--aliyunOSS-->
    <dependency>
        <groupId>com.aliyun.oss</groupId>
        <artifactId>aliyun-sdk-oss</artifactId>
        <version>2.8.3</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
</dependencies>
配置application.properties

不要多敲空格

#服务端口
server.port=8002
#服务名
spring.application.name=service-oss

#环境设置:dev、test、prod
spring.profiles.active=dev
        
#阿里云 OSS
#不同的服务器,地址不同
aliyun.oss.file.endpoint=your endpoint
aliyun.oss.file.keyid=your accessKeyId
aliyun.oss.file.keysecret=your accessKeySecret
#bucket可以在控制台创建,也可以使用java代码创建
aliyun.oss.file.bucketname=your bucketname
endpoint

这个根据你的服务区域有关,在创建Bucketname时有显,在概览中也有显示。
例如:华北2(北京)的endpoint:oss-cn-beijing.aliyuncs.com

AccessKey的获取

点击头像,有个AccessKey管理。建议创建并使用子用户。
在这里插入图片描述

启动类

spring boot 会默认加载org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration这个类,
而DataSourceAutoConfiguration类使用了@Configuration注解向spring注入了dataSource bean,又因为项目(oss模块)中并没有关于dataSource相关的配置信息,所以当spring创建dataSource bean时因缺少相关的信息就会报错。

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)//不加载数据数据库配置
@ComponentScan(basePackages = {"xxx"})
public class OssApplication {

    public static void main(String[] args) {
        SpringApplication.run(OssApplication.class, args);
    }
}
常量类

使用@Value读取application.properties里的配置内容
用spring的 InitializingBean 的 afterPropertiesSet 来初始化配置信息,这个方法将在所有的属性被初始化后调用。

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 常量类,读取配置文件application.properties中的配置
 */
@Component
//@PropertySource("classpath:application.properties")
public class ConstantPropertiesUtil 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 ACCESS_KEY_ID;
    public static String ACCESS_KEY_SECRET;
    public static String BUCKET_NAME;

    @Override
    public void afterPropertiesSet() throws Exception {
        END_POINT = endpoint;
        ACCESS_KEY_ID = keyId;
        ACCESS_KEY_SECRET = keySecret;
        BUCKET_NAME = bucketName;
    }
}
文件上传实现类
public class FileServiceImpl implements FileService {

	@Override
	public String upload(MultipartFile file) {
		//获取阿里云存储相关常量
		String endPoint = ConstantPropertiesUtil.END_POINT;
		String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
		String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
		String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
		//这个的作用是定义将上传文件放在哪个文件夹下面,由于我上面都没定义该变量,这个可以删除
		String fileHost = ConstantPropertiesUtil.FILE_HOST;
		
		String uploadUrl = null;
		try {
			//判断oss实例是否存在:如果不存在则创建,如果存在则获取
			OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
			if (!ossClient.doesBucketExist(bucketName)) {
				//创建bucket
				ossClient.createBucket(bucketName);
				//设置oss实例的访问权限:公共读
				ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
			}
			//获取上传文件流
			InputStream inputStream = file.getInputStream();
			//构建日期路径:avatar/2019/02/26/文件名
			String filePath = new DateTime().toString("yyyy/MM/dd");
			//文件名:uuid.扩展名
			String original = file.getOriginalFilename();
			String fileName = UUID.randomUUID().toString();
			String fileType = original.substring(original.lastIndexOf("."));
			String newName = fileName + fileType;
			String fileUrl = fileHost + "/" + filePath + "/" + newName;
			//文件上传至阿里云
			ossClient.putObject(bucketName, fileUrl, inputStream);
			// 关闭OSSClient。
			ossClient.shutdown();
			//获取url地址
			uploadUrl = "http://" + bucketName + "." + endPoint + "/" + fileUrl;
		} catch (IOException e) {
			throw new GuliException(ResultCodeEnum.FILE_UPLOAD_ERROR);
		}
		return uploadUrl;
	}
}
控制层
@Api(description="阿里云文件管理")
@CrossOrigin //跨域
@RestController
@RequestMapping("/admin/oss/file")
public class FileController {
	@Autowired
	private FileService fileService;
	/**
	 * 文件上传
	 *
	 * @param file
	 */
	@ApiOperation(value = "文件上传")
	@PostMapping("upload")
	public R upload(
			@ApiParam(name = "file", value = "文件", required = true)
			@RequestParam("file") MultipartFile file) {

		String uploadUrl = fileService.upload(file);
		//返回r对象
		return R.ok().message("文件上传成功").data("url", uploadUrl);

	}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值