栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot结合阿里云oss对象存储服务——实现图片上传

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot结合阿里云oss对象存储服务——实现图片上传

一、OSS基本配置 1.1 基本属性配置
#properties文件

# oss地域节点
aliyun.oss.file.endPoint=xxxxxxxxxx
# 阿里云key
aliyun.oss.file.keyId=xxxxxxxx
# 阿里云密钥
aliyun.oss.file.keySecret=xxxxxxxxxxxx
# oss的bucket名
aliyun.oss.file.bucketName=xxxxxxx
1.2 OSS初始化配置
package com.zhmsky.oss.utils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


@Component
@Api("OSS配置文件获取工具类")
public class OssPropertiesUtil implements InitializingBean {
    //读取oss配置文件,获取oss基本配置
    @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;

    @ApiModelProperty("地域节点")
    public static String END_POINT;

    @ApiModelProperty("阿里云key")
    public static String KEY_ID;

    @ApiModelProperty("阿里云密钥")
    public static String KEY_SECRET;

    @ApiModelProperty("水桶名")
    public static String BUCKET_NAME;


    
    @Override
    public void afterPropertiesSet() throws Exception {
        END_POINT=endPoint;
        KEY_ID=keyId;
        KEY_SECRET=keySecret;
        BUCKET_NAME=bucketName;
    }
}

InitializingBean是Spring提供的拓展性接口,InitializingBean接口为bean提供了属性初始化后的处理方法,它只有一个afterPropertiesSet方法,凡是继承该接口的类,在bean的属性初始化后都会执行该方法。

二、service
package com.zhmsky.oss.service;

import org.springframework.web.multipart.MultipartFile;


public interface OssService {
    
    String uploadOssAvatar(MultipartFile file);
}
2.1 serviceImpl
package com.zhmsky.oss.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.zhmsky.oss.service.OssService;
import com.zhmsky.oss.utils.OssPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;


@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadOssAvatar(MultipartFile file) {
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String endpoint = OssPropertiesUtil.END_POINT;
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = OssPropertiesUtil.KEY_ID;
        String accessKeySecret = OssPropertiesUtil.KEY_SECRET;
        // 填写Bucket名称,例如examplebucket。
        String bucketName = OssPropertiesUtil.BUCKET_NAME;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String url = "";
        try {
            InputStream inputStream = null;
            try {
                inputStream = file.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //得到上传的文件名
            String fileName = file.getOriginalFilename();
            //为了保证同名文件不被覆盖,添加随机值
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName = uuid + "-" + fileName;
            //把文件按照日期分类(建文件夹)
            String datePath = new DateTime().toString("yyyy/MM/dd");
            fileName = datePath + "/" + fileName;
            // 调用oss方法实现上传
            //第二个参数就是上传到oss的文件路径和文件名称
            ossClient.putObject(bucketName, fileName, inputStream);
            url = "https://" + bucketName + "." + endpoint + "/" + fileName;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return url;
    }
}
三、controller
@RestController
@RequestMapping("/ossService/file")
@Api("OSS云对象存储")
@CrossOrigin
public class OssController {
    @Autowired
    private OssService ossService;

    @PostMapping("/uploadOssFile")
    @ApiOperation("头像上传")
    public Result> uploadOssFile(@ApiParam("获取上传文件") MultipartFile file) {
        String url=ossService.uploadOssAvatar(file);
        Map map = new HashMap<>();
        map.put("url",url);
        return new ResultUtil>().setData(map);
    }
}
四、前端 3.1 html
     
        
          :on-success="handleAvatarSuccess"
          
          :before-upload="beforeAvatarUpload"
          
          :action="BASE_API + '/ossService/file/uploadOssFile'"
          
        >
          
          
        
      
3.2 js
    handleAvatarSuccess(res,file) {
      this.courseInfo.cover=res.result.url
    },

   //上传之前(规定文件类型、文件大小)
    beforeAvatarUpload(file) {
      //限定图片只能是jpg格式
      const isJPG = file.type === "image/jpeg";
      
      //限定图片大小不超过2M
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    }

到此大功告成!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/825980.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号