SpringBoot整合阿里OSS(一)__文件上传

1. 引入依赖文件

pom.xml



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.6.RELEASE
         
    
    com.jetlee
    oss
    0.0.1-SNAPSHOT
    oss
    Demo project for Spring Boot

    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    
        
        
            com.aliyun.oss
            aliyun-sdk-oss
            2.4.0
        
        
            commons-fileupload
            commons-fileupload
            1.3.1
        


    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



2. 配制文件

专门做一个配置文件,然后在使用中直接读取配置文件,这样方便后期管理,修改application.properties

# OSS相关配制
oss.file.endpoint=oss-cn-beijing.aliyuncs.com # 阿里云内网或者外网的访问地址
oss.file.keyid=# 阿里云控制台获取
oss.file.keysecret=# 阿里云控制台获取
oss.file.bucketname=jp-testfree #自己定义的块儿名称
oss.file.filehost=blog # 自己定义的路径名称

3. 定义常量类 ConstantProperties.java

常量类读取application.properties中定义的参数

package com.jetlee.oss.constant;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ConstantProperties implements InitializingBean {

    @Value("${oss.file.endpoint}")
    private String oss_file_endpoint;

    @Value("${oss.file.keyid}")
    private String oss_file_keyid;

    @Value("${oss.file.keysecret}")
    private String oss_file_keysecret;

    @Value("${oss.file.filehost}")
    private String oss_file_filehost;

    @Value("${oss.file.bucketname}")
    private String oss_file_bucketname;

    public static String OSS_END_POINT;
    public static String OSS_ACCESS_KEY_ID;
    public static String OSS_ACCESS_KEY_SECRET;
    public static String OSS_BUCKET_NAME;
    public static String OSS_FILE_HOST;


    @Override
    public void afterPropertiesSet() throws Exception{

        OSS_END_POINT=oss_file_endpoint;
        OSS_ACCESS_KEY_ID=oss_file_keyid;
        OSS_ACCESS_KEY_SECRET=oss_file_keysecret;
        OSS_BUCKET_NAME=oss_file_bucketname;
        OSS_FILE_HOST=oss_file_filehost;

    }
}

4. 编写阿里云工具类AliyunOSSUtil

package com.jetlee.oss.utils;

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.jetlee.oss.constant.ConstantProperties;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class AliyunOSSUtil {

    public static String upload(File file) {
        String endpoint = ConstantProperties.OSS_END_POINT;
        String accessKeyId = ConstantProperties.OSS_ACCESS_KEY_ID;
        String accessKeySecret = ConstantProperties.OSS_ACCESS_KEY_SECRET;
        String bucketName = ConstantProperties.OSS_BUCKET_NAME;
        String fileHost = ConstantProperties.OSS_FILE_HOST;

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());

        if (null == file) {
            return null;
        }

        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            //容器不存在,就创建
            if (!ossClient.doesBucketExist(bucketName)) {
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }
            //创建文件路径
            String fileUrl = fileHost + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") + "-" + file.getName());
            //上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            //设置权限 这里是公开读
            ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            if (null != result) {

                return fileUrl;
            }
        } catch (OSSException oe) {

        }
        finally {
            //关闭
            ossClient.shutdown();
        }
        return null;
    }
}

5. 写一个上传页面uplaod.html




    
    
    
    Document


文件:

6. 编写一个文件上传控制器

package com.jetlee.oss.controller;

import com.jetlee.oss.utils.AliyunOSSUtil;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;

@Controller
public class UploadController {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(UploadController.class);

    @RequestMapping(value = "/dealupload", method = RequestMethod.POST)
    public String uploadBlog(MultipartFile file) {

        try {

            if (null != file) {
                String filename = file.getOriginalFilename();
                if (!"".equals(filename.trim())) {
                    File newFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();
                    file.transferTo(newFile);
                    //上传到OSS
                    String uploadUrl = AliyunOSSUtil.upload(newFile);

                }

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "upload";
    }

    @RequestMapping(value = "/upload", method = RequestMethod.GET)
    public String toUploadBlog() {
        return "upload";
    }
}

7. 打开浏览器上传,控制台查看是否上传成功

image.png
image.png

你可能感兴趣的:(SpringBoot整合阿里OSS(一)__文件上传)