• 阿里云OSS整合


    一、对象存储OSS

    为了解决海量数据存储与弹性扩容(主要是静态文件的存储例如图片,语音,视频等),项目中我们通常采用云存储的解决方案- 阿里云OSS。

    1、开通“对象存储OSS”服务

    (1)申请阿里云账号
    (2)实名认证
    (3)开通“对象存储OSS”服务
    (4)进入管理控制台

    2、创建Bucket

    选择:标准存储、公共读、不开通
    在这里插入图片描述

    3、上传默认头像

    创建文件夹avatar,上传默认的用户头像
    在这里插入图片描述

    4、创建RAM子用户

    在这里插入图片描述
    在这里插入图片描述

    添加用户

    在这里插入图片描述
    在这里插入图片描述
    输入手机号验证码

    设置用户权限

    这里点击添加权限,使用的是OSS和VOD所以选择对象云存储和阿里云视频点播管理功能的权限。
    在这里插入图片描述

    获取子用户AccessKeyId,AccessKeySecret

    在这里插入图片描述

    使用Java SDK

    在这里插入图片描述

    1、创建Maven项目

    com.test.aliyun-oss

    2、pom

    <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>
    

    3、找到编码时需要用到的常量值

    (1)endpoint
    (2)bucketName
    (3)accessKeyId
    (4)accessKeySecret

    4、测试创建Bucket的连接

    在这里插入图片描述

    public class OSSTest {
    
        // Endpoint以杭州为例,其它Region请按实际情况填写。
        String endpoint = "your endpoint";
        // 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = "your accessKeyId";
        String accessKeySecret = "your accessKeySecret";
        String bucketName = "guli-file";
    
        @Test
        public void testCreateBucket() {
    
            // 创建OSSClient实例。
            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    
            // 创建存储空间。
            ossClient.createBucket(bucketName);
    
            // 关闭OSSClient。
            ossClient.shutdown();
        }
    }
    

    配置文件application.properties

    #服务端口
    server.port=8001
    #服务名
    spring.application.name=xuexi-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=edu-service-test101
    aliyun.oss.file.filehost=avatar
    

    从配置文件中读取常量

    创建常量读取工具类:ConstantPropertiesUtil.java
    使用@Value读取application.properties里的配置内容
    用spring的 InitializingBean 的 afterPropertiesSet 来初始化配置信息,这个方法将在所有的属性被初始化后调用。

    /**
     * 常量类,读取配置文件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.filehost}")
    	private String fileHost;
    
    	@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;
    	public static String FILE_HOST ;
    
    	@Override
    	public void afterPropertiesSet() throws Exception {
    		END_POINT = endpoint;
    		ACCESS_KEY_ID = keyId;
    		ACCESS_KEY_SECRET = keySecret;
    		BUCKET_NAME = bucketName;
    		FILE_HOST = fileHost;
    	}
    }
    

    文件上传

    public interface FileService {
    
    	/**
    	 * 文件上传至阿里云
    	 * @param file
    	 * @return
    	 */
    	String upload(MultipartFile file);
    }
    

    SDK中:Java->上传文件->简单上传->流式上传->上传文件流

    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;
    	}
    }
    

    controller

    @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);
    
    	}
    }
    

    之后可以通过swaggerui进行接口测试,值阿里云控制台中查看文件是否上传成功!

    以上有错误的地方尽情指出,一起学习进步!

  • 相关阅读:
    php 后端跨域请求
    IIS服务器文件跨域问题(几乎可以解决大多数跨域问题)
    JavaScript中的execCommand
    [原创] 利用前端+php批量生成html文件,传入新文本,输出新的html文件
    javascript 生成 uuid
    zabbix安装 检测环境 PHP bcmath off
    mysql中间件-amoeba
    MySQL备份
    ELK日志分析
    SAMBA配置文件详解
  • 原文地址:https://www.cnblogs.com/dataoblogs/p/14121833.html
Copyright © 2020-2023  润新知