spring boot基于阿里云OSS上传图片

作者: 小疯子 分类: Spring Boot,默认 发布时间: 2019-01-08 13:20

一、前言

就是简单记一下刚写完的上传功能

二、代码开发

  1. 设置阿里云OSS的基本配置在项目src/main/resources/application.yml文件下:
    feng:
      oss:
        endpoint: ****
        keyid: ******
        keysecret: ******
        bucketname1: ****
        filehost: **

    其中endpoint——你的endPoint,keyid——你的keyid,keysecret——你的keysecret,bucketname1——你的bucketname,filehost——你的目录,我写的是java

  2. 添加阿里云以及上传类的依赖
    <dependency>
        <groupId>com.aliyun.oss</groupId>
        <artifactId>aliyun-sdk-oss</artifactId>
        <version>2.8.3</version>
    </dependency>
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.3</version>
    </dependency>
  3. 添加阿里云OSS配置类,其中实现了InitializingBean,关于这个接口可以参考“Spring中的InitializingBean接口的使用——https://blog.csdn.net/shunfa888/article/details/80058722”的介绍
    package com.xiaofeng.pro.config.aliyunoss;
    
    import org.springframework.beans.factory.InitializingBean;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    
    /**
     * @program: people
     * @description: 阿里云配置
     * @author: dongxiaofeng
     * @create: 2018-12-19-11-23
     */
    @Component
    public class AliyunOssConfig implements InitializingBean {
        @Value("${feng.oss.endpoint}")
        private String ossEndpoint;
    
        @Value("${feng.oss.keyid}")
        private String ossKeyid;
    
        @Value("${feng.oss.keysecret}")
        private String ossKeysecret;
    
        @Value("${feng.oss.bucketname1}")
        private String ossBucketname1;
    
        @Value("${feng.oss.filehost}")
        private String ossFilehost;
    
        public  static  String OSS_FILE_ENDPOINT;
        public  static  String OSS_FILE_ACCESS_KEY_ID;
        public  static  String OSS_FILE_ACCESS_KEY_SECRET;
        public  static  String OSS_FILE_BUCKET_NAME1;
        public  static  String OSS_FILE_FILE_HOST;
    
        @Override
        public void afterPropertiesSet() throws Exception {
            OSS_FILE_ENDPOINT = ossEndpoint;
            OSS_FILE_ACCESS_KEY_ID = ossKeyid;
            OSS_FILE_ACCESS_KEY_SECRET = ossKeysecret;
            OSS_FILE_BUCKET_NAME1 = ossBucketname1;
            OSS_FILE_FILE_HOST = ossFilehost;
        }
    }
  4.  再进行上传工具类的编写:
    package com.xiaofeng.pro.common.utils;
    
    import com.aliyun.oss.ClientException;
    import com.aliyun.oss.OSSClient;
    import com.aliyun.oss.OSSException;
    import com.aliyun.oss.model.CannedAccessControlList;
    import com.aliyun.oss.model.CreateBucketRequest;
    import com.aliyun.oss.model.PutObjectRequest;
    import com.aliyun.oss.model.PutObjectResult;
    import com.xiaofeng.pro.config.aliyunoss.AliyunOssConfig;
    import lombok.extern.flogger.Flogger;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.stereotype.Component;
    
    import java.io.File;
    import java.net.URL;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.UUID;
    
    /**
     * @program: people
     * @description: 阿里云工具
     * @author: dongxiaofeng
     * @create: 2018-12-19-11-17
     */
    @Slf4j
    @Component
    public class AliyunOssUtil {
    
        public String upload(File file){
    
            String endpoint = AliyunOssConfig.OSS_FILE_ENDPOINT;
            String accessKeyId = AliyunOssConfig.OSS_FILE_ACCESS_KEY_ID;
            String accessKeySecret = AliyunOssConfig.OSS_FILE_ACCESS_KEY_SECRET;
            String bucketName = AliyunOssConfig.OSS_FILE_BUCKET_NAME1;
            String fileHost = AliyunOssConfig.OSS_FILE_FILE_HOST;
    
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String dateStr = format.format(new Date());
    
            OSSClient client = new OSSClient(endpoint,accessKeyId,accessKeySecret);
    
            //判断文件
            if(file == null){
                return null;
            }
            try {
                //判断容器是否存在,不存在就创建
                if (!client.doesBucketExist(bucketName)) {
                    client.createBucket(bucketName);
                    CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
    
                    createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                    client.createBucket(createBucketRequest);
                }
    
                //设置文件路径和名称
                String fileUrl = fileHost + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "")
                        + "-" + file.getName());
                //上传文件
                PutObjectResult result = client.putObject( new PutObjectRequest(bucketName, fileUrl, file));
                //设置权限
                client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
                if (result != null) {
                    System.out.println("-----文件上传成功----");//需要学一下日志怎么记录,学习日志部分的内容
                    String url = getUrl(client, bucketName, fileUrl);
                    return url;
                }
            }catch (OSSException oe){
                System.out.println(oe.getMessage());
            }catch (ClientException ce){
                System.out.println(ce.getErrorMessage());
            }finally {
                if(client != null){
                    client.shutdown();
                }
            }
            return null;
        }
    
        /**
         * 获得url链接
         */
        public String getUrl(OSSClient ossClient, String bucketName, String key){
            // 设置URL过期时间为10年  3600l* 1000*24*365*10
            Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
            URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
            if(url != null){
                return url.toString();
            }
            return null;
        }
    }
  5. 编写Controller来实现文件上传,上传后会得到上传成功后的文件在OSS中的路径返回给请求者做其他的操作:
    package com.xiaofeng.pro.controller.common;
    
    import com.xiaofeng.pro.common.utils.AliyunOssUtil;
    import com.xiaofeng.pro.common.utils.ResultUtil;
    import com.xiaofeng.pro.common.vo.Result;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.transaction.annotation.Transactional;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.MultipartFile;
    
    import javax.servlet.http.HttpServletRequest;
    import java.io.File;
    import java.io.FileOutputStream;
    
    /**
     * @program: people
     * @description: 文件上传功能,common目录下存放通用的controller
     * @author: dongxiaofeng
     * @create: 2018-12-19-10-27
     */
    @RestController
    @RequestMapping("/feng/upload")
    @Transactional
    public class UploadController {
    
        @Autowired
        private AliyunOssUtil aliyunOssUtil;
    
        /** 
        * @Description: request目前没有用,如果后期需要显示每个ip的传送次数需要这个获取到ip或其他请求信息
        * @Param: [file, request] 
        * @return: com.xiaofeng.pro.common.vo.Result<java.lang.Object> 
        * @Author: xiaofeng
        * @Date: 2018/12/19 
        */
        @RequestMapping(value = "/file", method = RequestMethod.POST)
        public Result<Object> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request){
            String result = null;
            String filename = file.getOriginalFilename();
            try{
                if(file != null){
                    if(!"".equals(filename.trim())){
                        File newFile = new File(filename);
                        FileOutputStream os = new FileOutputStream(newFile);
                        os.write(file.getBytes());
                        os.close();
                        file.transferTo(newFile);
                        //上传到oss
                        result = aliyunOssUtil.upload(newFile);
                    }
                }
            }catch (Exception ex){
                ex.printStackTrace();
            }
            return new ResultUtil<Object>().setData(result);
        }
    }
0