个人博客(9、使用七牛云作为文件存储工具)

137 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第11天,点击查看活动详情

一、前言

简略版博客后端只剩下文件模块没有完成了,本项目使用七牛云作为文件存储工具,减轻服务器压力。

二、对接七牛云

七牛云官方文档地址

七牛云官方文档(java)

七牛云令牌key和要保存图片的空间名称

image.png

image.png

pom引入七牛云依赖

<!-- 七牛云 -->
<dependency>
    <groupId>com.qiniu</groupId>
    <artifactId>qiniu-java-sdk</artifactId>
    <version>7.7.0</version>
</dependency>

七牛云demo()

简单地写了一下,因为现在七牛云文件存储要有域名,我还没有申请,所以只是简单的写了一下,新申请的七牛云账号有三十天的临时域名可以测试使用,可是我的让我给浪费了。。。

@PostMapping
@ApiOperation("新增")
public ResultVo insert(File fileDto, MultipartFile file) throws IOException {
    // 文件名
    String originalFilename = file.getOriginalFilename();
    // 文件流
    InputStream inputStream = file.getInputStream();
    String upload = qiNiuUtils.upload(file);
    fileDto.setUrl(upload);
    fileService.save(fileDto);
    return new ResultVo();
}
package com.ningxuan.blog.util;

import com.google.gson.Gson;
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 org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;

/**
 * 七牛云文件处理
 *
 * @Author ningxuan
 * @Date 2022/8/10 23:32
 */
@Component
public class QiNiuUtils {

    private String accessKey;

    private String secretKey;

    private String bucket;

    @Value("#{qiniu.accessKey}")
    public void setAccessKey(String accessKey) {
        this.accessKey = accessKey;
    }

    @Value("#{qiniu.scret}")
    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    @Value("#{qiniu.bucket}")
    public void setBucket(String bucket) {
        this.bucket = bucket;
    }

    public  String upload(MultipartFile file) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //默认不指定key的情况下,以文件内容的hash值作为文件名
        //TODO 待完善,随机字符串拼接文件名,避免重复
        String key = file.getOriginalFilename();
        try {
            byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(uploadBytes);
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            Response response = uploadManager.put(file.getInputStream(), key, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        } catch (Exception ex) {
            //ignore
        }
        return key;
    }

}

三、总结

简单的对接了一下七牛云的文件上传功能,对于图片和视频七牛云还有其他的接口可以把玩把玩,例如给图片添加水印什么的

接下来就要开搞前端的内容了,更的会细一点,毕竟虽然不是从零开始,但是也差不太多了