栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot简单实现上传图片到七牛云

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot简单实现上传图片到七牛云

前言

笔记参考

三更草堂

为什么?

​ 因为如果把图片视频等文件上传到自己的应用的Web服务器,在读取图片的时候会占用比较多的资源。影响应用服务器的性能。

​ 所以我们一般使用OSS(Object Storage Service对象存储服务)存储图片或视频。

快速开始 一、添加依赖

    com.qiniu
    qiniu-java-sdk
    [7.7.0, 7.7.99]

二、配置yml文件
qiniu-oss:
  # 密钥
  accessKey: q9xw_WzS18ZkZrpwmq16iILG0uZkqwdmlvq8omga
  secretKey: c2Y8CI201-WGHaQ2ng2yhgVfV9O_QeZZdUsdSRl_
  # 空间名称
  bucket: frozenpenguin
  # 七牛云提供的测试域名
  testUrl: http://rbx06lhom.bkt.clouddn.com/
三、编写代码 PathUtils

用于根据当前日期生成路径

public class PathUtils {

    public static String generateFilePath(String fileName){
        //根据日期生成路径   2022/1/15/
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        String datePath = sdf.format(new Date());
        //uuid作为文件名
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        //后缀和文件后缀一致
        int index = fileName.lastIndexOf(".");
        // test.jpg -> .jpg
        String fileType = fileName.substring(index);
        return new StringBuilder().append(datePath).append(uuid).append(fileType).toString();
    }
}
UploadController
@RestController
public class UploadController {
    @Autowired
    private UploadService uploadService;

    @PostMapping("/upload")
    public ResponseResult uploadImg(MultipartFile img){
        return uploadService.uploadImg(img);
    }
}
UploadService
public interface UploadService {
    ResponseResult uploadImg(MultipartFile img);
}
UploadServiceImpl
@Service
@Data
@ConfigurationProperties(prefix = "qiniu-oss")
public class OssUploadService implements UploadService {
    @Override
    public ResponseResult uploadImg(MultipartFile img) {
        //判断文件类型
        //获取原始文件名
        String originalFilename = img.getOriginalFilename();
        //对原始文件名进行判断(此处只允许png图片)
        if(!originalFilename.endsWith(".png")){
            //此处可以自定义抛出异常给前端
            //throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
            throw new RuntimeException("文件格式有误")
        }

        //如果判断通过上传文件到OSS
        String filePath = PathUtils.generateFilePath(originalFilename);
        String url = uploadOss(img,filePath);//  2099/2/3/wqeqeqe.png
        return ResponseResult.okResult(url);
    }

    private String accessKey;
    private String secretKey;
    private String bucket;
    private String testUrl;


    private String uploadOss(MultipartFile imgFile, String filePath){
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //默认不指定key的情况下,以文件内容的hash值作为文件名
        String key = filePath;
        try {
            InputStream inputStream = imgFile.getInputStream();
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(inputStream,key,upToken,null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
                return testUrl+key;//返回文件的url
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore
        }
        return "www";
    }
四、测试

这里使用ApiPost测试

请求路径:xxxx/upload

请求参数:img

请求类型:File

测试上传成功,在七牛云对应空间可以查看到相应的图片

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/891811.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号