zoukankan      html  css  js  c++  java
  • 在线教育项目-day05【上传头像功能】

    1.使用阿里云oss服务

     

     

     1.创建bucket

     2.配置

     

     

     3.使用

    就是上传文件

     我们要通过java代码上传文件

    1.首先要创建的Access key

     

     

     之后会发验证码

    2.查看如何使用

     

     引入依赖

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

    阿里云会给出代码

     3.书写代码及测试

    1.创建service_oss模块

     2.导入依赖

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

     3.创建配置文件

     这个就是自己的acess key

    #服务端口
    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=LTAI4G6wT9rRbhacy6YBj9Lt
    aliyun.oss.file.keysecret=04jdcJDdAgEJWD0pqLyf4smnW0Xou7
    #bucket可以在控制台创建,也可以使用java代码创建
    aliyun.oss.file.bucketname=edu-dumeng

    4.创建启动类

    OssApplication
    @SpringBootApplication
    @ComponentScan({"com.dm"}) 
    public class OssApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(OssApplication.class, args);
        }
    }

    启动一下

    会报错

     原因:

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

    启动成功:

     

     5.写上传文件的代码

    创建工具类ConstantPropertiesUtil

    使用@Value读取application.properties里的配置内容
    用spring的 InitializingBean 的 afterPropertiesSet 来初始化配置信息,这个方法将在所有的属性被初始化后调用。
    代码:
    @Component
    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;
        }
    
    
    }

    创建如下结构

    
    

    @Api(description="阿里云文件管理")
    @CrossOrigin //跨域
    @RestController
    @RequestMapping("/admin/oss/file")

    public class ossController {
        @Autowired
        private ossService ossService;
        //上传头像
        @PostMapping
        public R uploadFile(MultipartFile file){
            //获取上传文件
            String url=ossService.uploadFileAvatar(file);
    
            return R.OK().data("url",url);
        }
    }
    public interface ossService {
        public String uploadFileAvatar(MultipartFile file);
    
    }

    实现类写法我们可以参照阿里云给出的:

     最终代码:

    public class ossServiceImpl implements ossService {
        @Override
        public String uploadFileAvatar(MultipartFile file) {
    
            // 工具类获取值
            String endpoint = ConstantPropertiesUtil.END_POINT;
            String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
            String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
            String bucketName = ConstantPropertiesUtil.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 把文件按照日期进行分类
                //获取当前日期
                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;
            }
        }
    }

    遇到了一个bug

     大概意思就是没有找到ossService,经过查看这里没有加注解

  • 相关阅读:
    leetcode:Valid Parentheses(有效括号匹配)
    leetcode:Remove Nth Node From End of List (移除从尾部数的第N个节点)
    leetcode:Letter Combinations of a Phone Number(手机号码的字母组合)
    leetcode:4Sums(四个数相加的和)
    leetcode:3Sum Closest
    leetcode:3Sum (三个数的和)
    leetcode:Longest Common Prefix(取最长字符串前缀)
    php数据访问
    PHP 基础知识测试题
    面相对象设计模式
  • 原文地址:https://www.cnblogs.com/dmzna/p/12809176.html
Copyright © 2011-2022 走看看