zoukankan      html  css  js  c++  java
  • 阿里云OSS的使用

    1.打开阿里云网站:https://www.aliyun.com/

    2.注册阿里云,最终获取4个参数bucket 名称,endpoint ,Accesskey ID , Access key Secert

    3.搭建环境,引入maven依赖

        <!-- 阿里云oss依赖 -->
            <dependency>
                <groupId>com.aliyun.oss</groupId>
                <artifactId>aliyun-sdk-oss</artifactId>
            </dependency>
    
            <!-- 日期工具栏依赖 -->
            <dependency>
                <groupId>joda-time</groupId>
                <artifactId>joda-time</artifactId>
            </dependency>

    4.application.properties

    #服务端口
    server.port=8002
    #服务名
    spring.application.name=service_oss
    
    #环境设置:dev、test、prod
    spring.profiles.active=dev
    
    #阿里云 OSS
    #不同的服务器,地址不同
    aliyun.oss.file.endpoint=oss-cn-beijing.aliyuncs.com
    aliyun.oss.file.keyid=LTAI4Fi3Vq4jbugiWKrxnxtt
    aliyun.oss.file.keysecret=32qRznii5mTJCdyq9OimXMxCTiQJdr
    #bucket可以在控制台创建,也可以使用java代码创建
    aliyun.oss.file.bucketname=liuyi202044

    5.controller层

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

    6.创建一个工具类

    //当项目已启动,spring接口,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_POIND;
        public static String ACCESS_KEY_ID;
        public static String ACCESS_KEY_SECRET;
        public static String BUCKET_NAME;
    
        @Override
        public void afterPropertiesSet() throws Exception {
            END_POIND = endpoint;
            ACCESS_KEY_ID = keyId;
            ACCESS_KEY_SECRET = keySecret;
            BUCKET_NAME = bucketName;
        }
    }

    7.service层

    @Service
    public class OssServiceImpl implements OssService {
    
            @Override
            public String uploadFileAvatar(MultipartFile file) {
                // 工具类获取值
                String endpoint = ConstantPropertiesUtils.END_POIND;
                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();
    
                    //1 在文件名称里面添加随机唯一的值
                    String uuid = UUID.randomUUID().toString().replaceAll("-","");
                    // yuy76t5rew01.jpg
                    fileName = uuid+fileName;
    
                    //2 把文件按照日期进行分类
                    //获取当前日期
                    //   2019/11/12
                    String datePath = new DateTime().toString("yyyy/MM/dd");
                    //拼接
                    //  2019/11/12/ewtqr313401.jpg
                    fileName = datePath+"/"+fileName;
    
                    //调用oss方法实现上传
                    //第一个参数  Bucket名称
                    //第二个参数  上传到oss文件路径和文件名称   aa/bb/1.jpg
                    //第三个参数  上传文件输入流
                    ossClient.putObject(bucketName,fileName , inputStream);
    
                    // 关闭OSSClient。
                    ossClient.shutdown();
    
                    //把上传之后文件路径返回
                    //需要把上传到阿里云oss路径手动拼接出来
                    //  https://edu-guli-1010.oss-cn-beijing.aliyuncs.com/01.jpg
                    String url = "https://"+bucketName+"."+endpoint+"/"+fileName;
                    return url;
                }catch(Exception e) {
                    e.printStackTrace();
                    return null;
                }
            }
        }

    前端部分代码

    引入2个组件

    <!-- 讲师头像:TODO -->
          <!-- 讲师头像 -->
          <el-form-item label="讲师头像">
    
              <!-- 头衔缩略图 -->
              <pan-thumb :image="teacher.avatar"/>
              <!-- 文件上传按钮 -->
              <el-button type="primary" icon="el-icon-upload" @click="imagecropperShow=true">更换头像
              </el-button>
    
              <!--
          v-show:是否显示上传组件
          :key:类似于id,如果一个页面多个图片上传控件,可以做区分
          :url:后台上传的url地址
          @close:关闭上传组件
          @crop-upload-success:上传成功后的回调 
            <input type="file" name="file"/>
          -->
              <image-cropper
                            v-show="imagecropperShow"
                            :width="300"
                            :height="300"
                            :key="imagecropperKey"
                            :url="BASE_API+'/eduoss/fileoss'"
                            field="file"
                            @close="close"
                            @crop-upload-success="cropSuccess"/>
          </el-form-item>
    
    
    
    import ImageCropper from '@/components/ImageCropper'
    import PanThumb from '@/components/PanThumb'
    
    
    
    export default {
      components: { ImageCropper, PanThumb },
      data() {
        return {
          teacher:{
            name: '',
            sort: 0,
            level: 1,
            career: '',
            intro: '',
            avatar: ''
          },
          //上传弹框组件是否显示
          imagecropperShow:false,
          imagecropperKey:0,//上传组件key值
          BASE_API:process.env.BASE_API, //获取dev.env.js里面地址
          saveBtnDisabled:false  // 保存按钮是否禁用,
        }
      },
      created() { //页面渲染之前执行
        this.init()
      },
      watch: {  //监听
        $route(to, from) { //路由变化方式,路由发生变化,方法就会执行
          this.init()
        }
      },
      methods:{
        close() { //关闭上传弹框的方法
            this.imagecropperShow=false
            this.imagecropperKey=this.imagecropperKey+1
            
        },
        //上传成功方法
        cropSuccess(data) {
          this.imagecropperShow=false
          //上传之后接口返回图片地址
          this.teacher.avatar = data.url
          this.imagecropperKey=this.imagecropperKey+1
         
        },
        init() {
          //判断路径有id值,做修改
          if(this.$route.params && this.$route.params.id) {
              //从路径获取id值
              const id = this.$route.params.id
              //调用根据id查询的方法
              this.getInfo(id)
          } else { //路径没有id值,做添加
            //清空表单
            this.teacher = {}
          }
        },
        //根据讲师id查询的方法
        getInfo(id) {
          teacherApi.getTeacherInfo(id)
            .then(response => {
              this.teacher = response.data.teacher
            })
        },
        saveOrUpdate() {
          //判断修改还是添加
          //根据teacher是否有id
          if(!this.teacher.id) {
            //添加
            this.saveTeacher()
          } else {
            //修改
            this.updateTeacher()
          }
        },
        //修改讲师的方法
        updateTeacher() {
          teacherApi.updateTeacherInfo(this.teacher)
            .then(response => {
              //提示信息
              this.$message({
                  type: 'success',
                  message: '修改成功!'
              });
              //回到列表页面 路由跳转
              this.$router.push({path:'/teacher/table'})
            })
        },
        //添加讲师的方法
        saveTeacher() {
          teacherApi.addTeacher(this.teacher)
            .then(response => {//添加成功
              //提示信息
              this.$message({
                  type: 'success',
                  message: '添加成功!'
              });
              //回到列表页面 路由跳转
              this.$router.push({path:'/teacher/table'})
            })
        }
    
      }
    }
    </script>
  • 相关阅读:
    【Python】使用hashlib进行MD5和sha1摘要计算
    【Python】torrentParser1.04 增加获得磁力链URI功能
    day30_Hibernate复习_02
    day30_Hibernate学习笔记_02
    day29_Hibernate复习_01
    day29_Hibernate学习笔记_01
    【重要】Spring在web.xml中的配置原理说明
    HTTP常见错误编号
    一级缓存和二级缓存的理解
    电商网站前台与后台系统架构
  • 原文地址:https://www.cnblogs.com/liuyi13535496566/p/12640191.html
Copyright © 2011-2022 走看看