前言

七牛云为每个用户提供了10G免费存储空间。个人使用还是很香的。本文将记录如何上传文件。


一、环境准备

1. 账号准备

注册七牛云账号并实名

https://s.qiniu.com/b2qUry

创建对象存储空间

https://portal.qiniu.com/kodo/bucket
在这里插入图片描述

获取密钥

https://portal.qiniu.com/user/key

在这里插入图片描述
注意保管好自己的密钥

2. 创建spring boot 项目

在这里插入图片描述

pom.xml


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

        <dependency>
            <groupId>com.qiniu</groupId>
            <artifactId>qiniu-java-sdk</artifactId>
<!--            这里的version指定了一个版本范围,每次更新pom.xml的时候会尝试去下载7.7.x版本中的最新版本,你可以手动指定一个固定的版本。-->
            <version>[7.7.0, 7.10.99]</version>
        </dependency>

        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.14.2</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.qiniu</groupId>
            <artifactId>happy-dns-java</artifactId>
            <version>0.1.6</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.71</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

注意:从 7.2.24 开始,okhttp3 升级到 3.14.2,其要求 java 1.8 及以上。
若一定 java 1.7 ,请手动指定 okhttp3 依赖 3.12,要求 3.12.3 及以上

application.yml

logging:
  level:
    root: warn
    com.king: info
    org.springframework: error

Qiniu:
  AccessKey: xxxxxxxxxxx上述步骤获取密钥 你的AccessKey
  SecretKey: xxxxxxxxxx你的SecretKey xxxxxxxxxxxxxxxx
  
spring:
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 10MB

二、上传本地文件测试

QiniuServiceImpl.java

代码如下:

package com.king.oss.service;

import com.alibaba.fastjson.JSON;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author: 12613
 * @project: mooc
 * @pcakage: com.king.mooc.service.impl.QiniuServiceImpl
 * @date: 2022年05月02日 00:38
 * @description:
 */
@Service
public class QiniuServiceImpl {
    @Value(value = "${Qiniu.AccessKey}")
    private String accessKey;
    @Value(value = "${Qiniu.SecretKey}")
    private String secretKey;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //测试文件上传
    public void testUpload() {
        //构造一个带指定 Region 对象的配置类,指定存储区域,和存储空间选择的区域一致
        //
        Configuration cfg = new Configuration(Region.huanan());
        //其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //生成上传凭证,然后准备上传
        String bucket = "hnking";
        //默认不指定key的情况下,以文件内容的hash值作为文件名
        String key = UUID.randomUUID() + ".png";
        FileInputStream fileInputStream = null;
        try {

            String filePath = "C:\\Users\\12613\\Pictures\\20201029195525.png";
            fileInputStream = new FileInputStream(new File(filePath));
            //得到本地文件的字节数组
            byte[] bytes = IOUtils.toByteArray(fileInputStream);
            //认证
            Auth auth = Auth.create(accessKey, secretKey);
            //认证通过后得到token(令牌)
            String upToken = auth.uploadToken(bucket);
            try {
                //上传文件,参数:字节数组,key,token令牌
                //key: 建议我们自已生成一个不重复的名称
                Response response = uploadManager.put(bytes, key, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = JSON.parseObject(response.bodyString(),
                        DefaultPutRet.class);
                logger.info("上传成功{}", JSON.toJSONString(putRet));
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                   logger.error("上传失败{}",ex2.getMessage());
                }
            }
        } catch (IOException ex) {
            logger.error("上传文件失败", ex); 
        }

    }
}

测试代码

QiniuServiceImplTest.java

package com.king.oss.service;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class QiniuServiceImplTest {

    @Autowired
    private QiniuServiceImpl qiniuService;


    @Test
    public void uploadFile() {
        qiniuService.testUpload();
    }

}

运行结果
在这里插入图片描述
使用七牛云提供的测试域名
rb3lparfv.hn-bkt.clouddn.com/834c9118-ee9e-4d31-a247-5998d9ddbeed.png
即可访问图片


三、从浏览器上传文件

这里先参考之前的文章:SpringBoot 使用表单或者vue实现文件上传

修改后的 FileController.java

package com.king.oss.controller;

import com.king.oss.service.QiniuServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
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.IOException;
import java.util.Collections;
import java.util.List;

/**
 * @program: springboot
 * @description:
 * @author: King
 * @create: 2022-01-30 23:09
 */
@RestController
@RequestMapping("/file")
public class FileController {

    //默认上传到的路径

    @Autowired
    QiniuServiceImpl qiniuService;

    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile uploadFile, HttpServletRequest req) {
        if (!uploadFile.isEmpty()) {
            return qiniuService.saveFile(uploadFile);
        }
        return "上传失败!";
    }

    @PostMapping("/uploads")
    public List<String> upload(@RequestParam("files") MultipartFile[] uploadFiles, HttpServletRequest req) {
        if (!ObjectUtils.isEmpty(uploadFiles) && uploadFiles.length > 0) {
            return qiniuService.saveFile(uploadFiles);
        }
        return Collections.singletonList("上传失败!");
    }


}

修改后的QiniuServiceImpl.java

package com.king.oss.service;

import com.alibaba.fastjson.JSON;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author: 12613
 * @project: mooc
 * @pcakage: com.king.mooc.service.impl.QiniuServiceImpl
 * @date: 2022年05月02日 00:38
 * @description:
 */
@Service
public class QiniuServiceImpl {
    @Value(value = "${Qiniu.AccessKey}")
    private String accessKey;
    @Value(value = "${Qiniu.SecretKey}")
    private String secretKey;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    public String saveFile(MultipartFile uploadFile) {
        Configuration cfg = new Configuration(Region.huanan());
        UploadManager uploadManager = new UploadManager(cfg);
        String bucket = "hnking";
        String fileName = uploadFile.getOriginalFilename();
        String key = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(uploadFile.getBytes(), key, upToken);
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            return "http://rb3lparfv.hn-bkt.clouddn.com/" + putRet.key;
        } catch (QiniuException e) {
            logger.error("上传文件失败", e);
            logger.error(JSON.toJSONString(e.response));
        } catch (IOException e) {
            logger.error("上传文件失败", e);
        }
        return null;
    }

    public List<String> saveFile(MultipartFile[] uploadFiles) {
        List<String> list = new ArrayList<>();
        for (MultipartFile uploadFile : uploadFiles) {
            list.add(saveFile(uploadFile));
        }
        return list;
    }
}

在这里插入图片描述
http://rb3lparfv.hn-bkt.clouddn.com/ff63da0f-bbe2-4f96-9edd-531ec98ffdd1.png

ok 完美运行


四、源码地址

Github https://github.com/KingJin-web/springboot

Gitee https://gitee.com//KingJin-web/springboot

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐