阿里云对象存储OSS

    技术2022-07-10  155

    一、上传文件到阿里云OSS操作 1.获取ID秘钥 2.使用SDK 参考文档 https://help.aliyun.com/document_detail/32009.html?spm=a2c4g.11186623.6.779.204ec06dp2VO4A

    引入依赖

    <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.10.2</version> </dependency>

    配置 新建一个工具类获取配置中的信息

    //当项目已启动,spring接口(InitializingBean),spring加载之后,执行接口一个方法 @Component 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 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; } }

    service层

    @Service public class OssServiceImpl implements OssService { @Override public String uploadFileAvatar(MultipartFile file) { //通过工具类获取值 String endpoint = ConstantPropertiesUtils.END_POINT; String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID; String accessKeySecret =ConstantPropertiesUtils.ACCESS_KEY_SECRET; String bucketName=ConstantPropertiesUtils.BUCKET_NAME; try { //创建OSS实例 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 上传文件流。 InputStream inputStream = file.getInputStream(); //获取文件名称 String fileName = file.getOriginalFilename(); //在文件名称里添加随机的唯一的值 String uuid = UUID.randomUUID().toString().replaceAll("-",""); //guit8gif01.jpg fileName =uuid+fileName; //把文件按照日期分类 //2020/07/01/guit8gif01.jpg //获取当前日期 String datePath = new DateTime().toString("yyyy/MM/dd"); fileName=datePath+"/"+fileName; //调用oss方法实现上传 //第二个参数 上传到oss文件路径和文件名称 、aa/bb/1.jpg ossClient.putObject(bucketName, fileName, inputStream); // 关闭OSSClient。 ossClient.shutdown(); //需要把上传到阿里云oss路径手动拼接起来 //https://kundi-demo.oss-cn-beijing.aliyuncs.com/熊出没.jpg String url="https://"+endpoint+"."+bucketName+"/"+fileName; return url; }catch (Exception e){ e.printStackTrace(); } return null; } }

    controller层

    @RestController @RequestMapping("/oss/fileoss") public class OssController { @Autowired private OssService ossService; //上传方法 @PostMapping("/uploadOssFile") public R uploadOssFile(@RequestBody MultipartFile file){ //获取上传文件 MultipartFile //返回上传到oss的路径 String url = ossService.uploadFileAvatar(file); return R.ok().data("url",url); } }

    测试成功

    Processed: 0.020, SQL: 9