Spring Boot 使用七牛云上传文件

引入pom依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>com.qiniu</groupId>
    <artifactId>qiniu-java-sdk</artifactId>
    <version>7.2.27</version>
</dependency>

修改application.yaml配置文件

server:
  port: 8888

# 七牛云图片上传相关配置
upload:
  qiniu:
    domain: http://img.dbnewyouth.cn
    # 七牛云密钥管理中查看
    access-key: *****************
    # 七牛云密钥管理中查看
    secret-key: *****************
    bucket: dbnewyouth

习惯性定义一个全局返回结果

public class Result<T> {

    private Integer code;
    private String message;
    private T data;

    public Result(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

    public Result(Integer code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }
}

编写文件上传工具类

@Configuration
public class QiniuUtil {

    /**
     * 七牛云accesskey
     */
    private static String accessKey;
    /**
     * 七牛云secretkey
     */
    private static String secretKey;
    /**
     * 七牛云解析的图片域名
     */
    private static String domain;
    /**
     * 七牛云存储空间名称
     */
    private static String bucket;

    /**
     * 七牛云上传管理对象
     */
    private static UploadManager uploadManager = new UploadManager(new com.qiniu.storage.Configuration(Region.region0()));

    /**
     * 上传文件
     *
     * @param file 文件
     * @return 返回上传结果
     * @date 2019/12/19 15:51
     */
    public static Result uploadFile(MultipartFile file) {
        if (file.isEmpty()) {
            return new Result(9001, "文件不能为空");
        }
        // 拿到文件名
        String originalFilename = file.getOriginalFilename();
        // 校验文件类型
        String contentType = getContentType(originalFilename);
        if (contentType.isEmpty()) {
            return new Result(9002, "文件类型不合法");
        }
        // 获取一个七牛云的token
        String token = generateAuthToken();
        // 生成新文件名
        String newFileName = generateFileName(originalFilename);
        try {
            Response response = uploadManager.put(file.getInputStream(), newFileName, token, null, null);
            if (response.isOK()) {
                StringBuilder builder = new StringBuilder();
                builder.append(domain);
                builder.append("/");
                builder.append(newFileName);
                return new Result(200, "图片上传成功", builder.toString());
            } else {
                return new Result(9003, "上传失败", response.error);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(9003, "上传失败");
    }

    /**
     * 生成新文件名
     *
     * @param originalFilename 当前文件名(带后缀)
     * @return 返回新文件名
     * @date 2019/12/19 15:52
     */
    private static String generateFileName(String originalFilename) {
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        return UUID.randomUUID().toString() + suffix;
    }

    /**
     * 生成一个七牛云token
     *
     * @return 返回可用token
     * @date 2019/12/19 15:52
     */
    private static String generateAuthToken() {
        Auth auth = Auth.create(accessKey, secretKey);
        return auth.uploadToken(bucket);
    }

    /**
     * 文件类型,校验是否非法
     *
     * @param fileName 文件名
     * @return 返回当前文件类型
     * @date 2019/12/19 15:53
     */
    private static String getContentType(String fileName) {
        // 文件的后缀名
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        if (".bmp".equalsIgnoreCase(fileExtension)) {
            return "image/bmp";
        }
        if (".gif".equalsIgnoreCase(fileExtension)) {
            return "image/gif";
        }
        if (".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension)
                || ".png".equalsIgnoreCase(fileExtension)) {
            return "image/jpeg";
        }
        if (".png".equalsIgnoreCase(fileExtension)) {
            return "image/png";
        }
        if (".html".equalsIgnoreCase(fileExtension)) {
            return "text/html";
        }
        if (".txt".equalsIgnoreCase(fileExtension)) {
            return "text/plain";
        }
        if (".vsd".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.visio";
        }
        if (".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if (".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
            return "application/msword";
        }
        if (".xml".equalsIgnoreCase(fileExtension)) {
            return "text/xml";
        }
        // 默认返回类型
        return "";
    }

    public String getAccessKey() {
        return accessKey;
    }

    @Value("${upload.qiniu.access-key}")
    public void setAccessKey(String accessKey) {
        QiniuUtil.accessKey = accessKey;
    }

    public String getSecretKey() {
        return secretKey;
    }

    @Value("${upload.qiniu.secret-key}")
    public void setSecretKey(String secretKey) {
        QiniuUtil.secretKey = secretKey;
    }

    public String getDomain() {
        return domain;
    }

    @Value("${upload.qiniu.domain}")
    public void setDomain(String domain) {
        QiniuUtil.domain = domain;
    }

    public String getBucket() {
        return bucket;
    }

    @Value("${upload.qiniu.bucket}")
    public void setBucket(String bucket) {
        QiniuUtil.bucket = bucket;
    }
}

编写测试使用的controller

@RestController
@RequestMapping("/test")
public class TestController {

    /**
     * 文件上传
     *
     * @param file 上传的文件
     * @return 返回上传结果
     * @date 2019/12/19 15:53
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        Result result = QiniuUtil.uploadFile(file);
        return result;
    }
}

测试效果

使用postman进行文件上传

链接如下:http://img.dbnewyouth.cn/5f8aa23b-1c73-407a-842b-399e5fc51c93.jpg

图片效果

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×