通过官方SDK对腾讯云、阿里云、七牛云文件上传和本地存储文件上传,自由切换

avatar 2019年05月19日11:08:41 8 7279 views
博主分享免费Java教学视频,B站账号:Java刘哥 ,长期提供技术问题解决、项目定制:本站商品点此
因为博主之前七牛云被刷了波流量,损失惨重,目前不考虑使用七牛云了,会考虑阿里云、腾讯云和本地上传。

本文介绍 SpringBoot下,实现多种上传方式。

一、设计思路


现在的设计是想在后台可以设置文件存储位置,支持动态切换。

界面如下,管理员在系统设置里可以选择系统文件上传位置。



实现思路,存储当前上传方式(本地,七牛云,阿里云,腾讯云),如选择了腾讯云,填好了bucket、地域、ak、sk、访问域名后,将该配置信息记录在redis中,当然也可以考虑持久化到 mysql 中。

当用户上传文件,如上传头像,调用上传通用接口,如 /upload/file 接口,在该方法内判断当前存储方式,查到是腾讯云,调用腾讯云的上传Service接口。



下面一一介绍这几种实现,只贴核心代码,有开发经验的朋友应该能直接看懂。


二、腾讯云OSS创建


1.开通COS,创建bucket

进入腾讯云后台,在云产品下拉选择项里选择对象存储(简称OSS或COS),然后开通COS。

创建存储桶(bucket),名称自定义,所属地域可以选择离自己近的地方,访问权限如果需要对外访问可以选择公有读私有写。直达链接



2.查看空间名称(bucket)和访问域名(endpoint)



如 bucket 为 test-123456789

endpoint 为 test-1253316749.cos.ap-shanghai.myqcloud.com



3.创建密钥

在侧边栏有密钥管理,直达链接,在云密钥里创建和查看密钥,需要里面的SecretId和SecretKey

如SecretId:SWhswSWjswwnjSW21SWjswhuwHswhusswhu2

SecretKey:1swhuwjisn2hshu0-swnsw-1nswjswjko2s3





七牛云和阿里云以前介绍过,这里就不写了,步骤都差不多,目的都是需要有 bucket 名称,访问域名,sk,sk 等。

需要注意几点:

① 地域很重要,需要和配置里对应,因为不同的地域的标识是不一样的

② 如果访问不了文件,可能是访问权限的问题

③ ak 和 sk不要暴露


三、代码实战


1.上传入口类,UploadController.java
  1. package cn.exrick.xboot.modules.base.controller;
  2. import com.liuyanzhao.sens.common.constant.CommonConstant;
  3. importcom.liuyanzhao.sens.common.constant.SettingConstant;
  4. import com.liuyanzhao.senscommon.utils.*;
  5. import com.liuyanzhao.sens.common.vo.Result;
  6. import com.liuyanzhao.sens.modules.base.entity.File;
  7. import cn.hutool.core.util.StrUtil;
  8. import lombok.extern.slf4j.Slf4j;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.data.redis.core.StringRedisTemplate;
  11. import org.springframework.web.bind.annotation.RequestMapping;
  12. import org.springframework.web.bind.annotation.RequestMethod;
  13. import org.springframework.web.bind.annotation.RequestParam;
  14. import org.springframework.web.bind.annotation.RestController;
  15. import org.springframework.web.multipart.MultipartFile;
  16. import javax.servlet.http.HttpServletRequest;
  17. import java.io.InputStream;
  18. /**
  19.  * @author saysky
  20.  */
  21. @Slf4j
  22. @RestController
  23. @RequestMapping("/upload")
  24. public class UploadController {
  25.     @Autowired
  26.     private QiniuUtil qiniuUtil;
  27.     @Autowired
  28.     private AliOssUtil aliOssUtil;
  29.     @Autowired
  30.     private TencentOssUtil tencentOssUtil;
  31.     @Autowired
  32.     private FileUtil fileUtil;
  33.     @Autowired
  34.     private StringRedisTemplate redisTemplate;
  35.     @RequestMapping(value = "/file", method = RequestMethod.POST)
  36.     public Result<Object> upload(@RequestParam(required = false) MultipartFile file,
  37.                                  @RequestParam(required = false) String base64,
  38.                                  HttpServletRequest request) {
  39.         String used = redisTemplate.opsForValue().get(SettingConstant.OSS_USED);
  40.         if(StrUtil.isBlank(used)) {
  41.             return new ResultUtil<Object>().setErrorMsg(501"您还未配置OSS服务");
  42.         }
  43.         if(StrUtil.isNotBlank(base64)){
  44.             // base64上传
  45.             file = Base64DecodeMultipartFile.base64Convert(base64);
  46.         }
  47.         String result = "";
  48.         //重命名文件,UUID+后缀
  49.         String fKey = CommonUtil.renamePic(file.getOriginalFilename());
  50.         File f = new File();
  51.         try {
  52.             InputStream inputStream = file.getInputStream();
  53.             // 上传至第三方云服务或服务器
  54.             if(used.equals(SettingConstant.QINIU_OSS)){
  55.                 //七牛云上传
  56.                 result = qiniuUtil.qiniuInputStreamUpload(inputStream, fKey);
  57.                 f.setLocation(CommonConstant.OSS_QINIU);
  58.             }else if(used.equals(SettingConstant.ALI_OSS)){
  59.                 //阿里云上传
  60.                 result = aliOssUtil.aliInputStreamUpload(inputStream, fKey);
  61.                 f.setLocation(CommonConstant.OSS_ALI);
  62.             }else if(used.equals(SettingConstant.TENCENT_OSS)){
  63.                 //腾讯云上传
  64.                 result = tencentOssUtil.tencentInputStreamUpload(file, inputStream, fKey);
  65.                 f.setLocation(CommonConstant.OSS_TENCENT);
  66.             }else if(used.equals(SettingConstant.LOCAL_OSS)){
  67.                 //本地上传
  68.                 result = fileUtil.localUpload(file, fKey);
  69.                 f.setLocation(CommonConstant.OSS_LOCAL);
  70.             }
  71.             // 文件信息保存数据信息至数据库
  72.             //略
  73.         } catch (Exception e) {
  74.             log.error(e.toString());
  75.             return new ResultUtil<Object>().setErrorMsg(e.toString());
  76.         }
  77.         return new ResultUtil<Object>().setData(result);
  78.     }
  79. }



2.后台保存OSS配置接口 SettingController.java
  1. @RequestMapping(value = "/oss/set", method = RequestMethod.POST)
  2.    @ApiOperation(value = "OSS配置")
  3.    public Result<Object> ossSet(@ModelAttribute OssSetting ossSetting) {
  4.        if(ossSetting.getServiceName().equals(SettingConstant.QINIU_OSS)){
  5.            // 七牛
  6.            String v = redisTemplate.opsForValue().get(SettingConstant.QINIU_OSS);
  7.            if(StrUtil.isNotBlank(v)&&!ossSetting.getChanged()){
  8.                String secrectKey = new Gson().fromJson(v, OssSetting.class).getSecretKey();
  9.                ossSetting.setSecretKey(secrectKey);
  10.            }
  11.            redisTemplate.opsForValue().set(SettingConstant.QINIU_OSS, new Gson().toJson(ossSetting));
  12.            redisTemplate.opsForValue().set(SettingConstant.OSS_USED, SettingConstant.QINIU_OSS);
  13.        }else if(ossSetting.getServiceName().equals(SettingConstant.ALI_OSS)){
  14.            // 阿里
  15.            String v = redisTemplate.opsForValue().get(SettingConstant.ALI_OSS);
  16.            if(StrUtil.isNotBlank(v)&&!ossSetting.getChanged()){
  17.                String secrectKey = new Gson().fromJson(v, OssSetting.class).getSecretKey();
  18.                ossSetting.setSecretKey(secrectKey);
  19.            }
  20.            redisTemplate.opsForValue().set(SettingConstant.ALI_OSS, new Gson().toJson(ossSetting));
  21.            redisTemplate.opsForValue().set(SettingConstant.OSS_USED, SettingConstant.ALI_OSS);
  22.        }else if(ossSetting.getServiceName().equals(SettingConstant.TENCENT_OSS)){
  23.            // 腾讯
  24.            String v = redisTemplate.opsForValue().get(SettingConstant.TENCENT_OSS);
  25.            if(StrUtil.isNotBlank(v)&&!ossSetting.getChanged()){
  26.                String secrectKey = new Gson().fromJson(v, OssSetting.class).getSecretKey();
  27.                ossSetting.setSecretKey(secrectKey);
  28.            }
  29.            redisTemplate.opsForValue().set(SettingConstant.TENCENT_OSS, new Gson().toJson(ossSetting));
  30.            redisTemplate.opsForValue().set(SettingConstant.OSS_USED, SettingConstant.TENCENT_OSS);
  31.        }else if(ossSetting.getServiceName().equals(SettingConstant.LOCAL_OSS)){
  32.            // 本地
  33.            redisTemplate.opsForValue().set(SettingConstant.LOCAL_OSS, new Gson().toJson(ossSetting));
  34.            redisTemplate.opsForValue().set(SettingConstant.OSS_USED, SettingConstant.LOCAL_OSS);
  35.        }
  36.        return new ResultUtil<Object>().setData(null);
  37.    }



OSS配置封装类 OssSetting.java
  1. package com.liuyanzhao.sens.modules.base.vo;
  2. import lombok.Data;
  3. import java.io.Serializable;
  4. /**
  5.  * @author saysky
  6.  */
  7. @Data
  8. public class OssSetting implements Serializable{
  9.     private String serviceName;
  10.     private String accessKey;
  11.     private String secretKey;
  12.     private String endpoint;
  13.     private String bucket;
  14.     private String http;
  15.     private Integer zone;
  16.     private String bucketRegion;
  17.     private String filePath;
  18.     private Boolean changed;
  19. }



变量接口 SettingConstant.java
  1. package com.liuyanzhao.sens.common.constant;
  2. /**
  3.  * @author saysky
  4.  */
  5. public interface SettingConstant {
  6.     /**
  7.      * 当前使用OSS
  8.      */
  9.     String OSS_USED = "OSS_USED";
  10.     /**
  11.      * 七牛OSS配置
  12.      */
  13.     String QINIU_OSS = "QINIU_OSS";
  14.     /**
  15.      * 七牛云存储区域 自动判断
  16.      */
  17.     Integer ZONE_AUTO = -1;
  18.     /**
  19.      * 七牛云存储区域 华东
  20.      */
  21.     Integer ZONE_ZERO = 0;
  22.     /**
  23.      * 七牛云存储区域 华北
  24.      */
  25.     Integer ZONE_ONE = 1;
  26.     /**
  27.      * 七牛云存储区域 华南
  28.      */
  29.     Integer ZONE_TWO = 2;
  30.     /**
  31.      * 七牛云存储区域 北美
  32.      */
  33.     Integer ZONE_THREE = 3;
  34.     /**
  35.      * 七牛云存储区域 东南亚
  36.      */
  37.     Integer ZONE_FOUR = 4;
  38.     /**
  39.      * 阿里OSS配置
  40.      */
  41.     String ALI_OSS = "ALI_OSS";
  42.     /**
  43.      * 腾讯COS配置
  44.      */
  45.     String TENCENT_OSS = "TENCENT_OSS";
  46.     /**
  47.      * 本地OSS配置
  48.      */
  49.     String LOCAL_OSS = "LOCAL_OSS";
  50. }



3.具体的上传实现接口

① 七牛云 QiniuUtil.java
  1. package com.liuyanzhao.sens.common.utils;
  2. import com.liuyanzhao.sens.common.constant.SettingConstant;
  3. import com.liuyanzhao.sens.modules.base.vo.OssSetting;
  4. import com.liuyanzhao.sens.common.exception.SensException;
  5. import cn.hutool.core.util.StrUtil;
  6. import com.google.gson.Gson;
  7. import com.qiniu.common.QiniuException;
  8. import com.qiniu.common.Zone;
  9. import com.qiniu.http.Response;
  10. import com.qiniu.storage.BucketManager;
  11. import com.qiniu.storage.Configuration;
  12. import com.qiniu.storage.UploadManager;
  13. import com.qiniu.storage.model.DefaultPutRet;
  14. import com.qiniu.util.Auth;
  15. import lombok.extern.slf4j.Slf4j;
  16. import org.springframework.beans.factory.annotation.Autowired;
  17. import org.springframework.data.redis.core.StringRedisTemplate;
  18. import org.springframework.stereotype.Component;
  19. import java.io.InputStream;
  20. /**
  21.  * @author saysky
  22.  */
  23. @Slf4j
  24. @Component
  25. public class QiniuUtil {
  26.     @Autowired
  27.     private StringRedisTemplate redisTemplate;
  28.     public OssSetting getOssSetting(){
  29.         String v = redisTemplate.opsForValue().get(SettingConstant.QINIU_OSS);
  30.         if(StrUtil.isBlank(v)){
  31.             throw new SensException("您还未配置七牛云OSS");
  32.         }
  33.         return new Gson().fromJson(v, OssSetting.class);
  34.     }
  35.     public Configuration getConfiguration(Integer zone){
  36.         Configuration cfg = null;
  37.         if(zone.equals(SettingConstant.ZONE_ZERO)){
  38.             cfg = new Configuration(Zone.zone0());
  39.         }else if(zone.equals(SettingConstant.ZONE_ONE)){
  40.             cfg = new Configuration(Zone.zone1());
  41.         }else if(zone.equals(SettingConstant.ZONE_TWO)){
  42.             cfg = new Configuration(Zone.zone2());
  43.         }else if(zone.equals(SettingConstant.ZONE_THREE)){
  44.             cfg = new Configuration(Zone.zoneNa0());
  45.         }else if(zone.equals(SettingConstant.ZONE_FOUR)){
  46.             cfg = new Configuration(Zone.zoneAs0());
  47.         }else {
  48.             cfg = new Configuration(Zone.autoZone());
  49.         }
  50.         return cfg;
  51.     }
  52.     public UploadManager getUploadManager(Configuration cfg){
  53.         UploadManager uploadManager = new UploadManager(cfg);
  54.         return uploadManager;
  55.     }
  56.     /**
  57.      * 文件路径上传
  58.      * @param filePath
  59.      * @param key 文件名
  60.      * @return
  61.      */
  62.     public String qiniuUpload(String filePath, String key) {
  63.         OssSetting os = getOssSetting();
  64.         Auth auth = Auth.create(os.getAccessKey(), os.getSecretKey());
  65.         String upToken = auth.uploadToken(os.getBucket());
  66.         try {
  67.             Response response = getUploadManager(getConfiguration(os.getZone())).put(filePath, key, upToken);
  68.             DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
  69.             return os.getHttp() + os.getEndpoint() + "/" + putRet.key;
  70.         } catch (QiniuException ex) {
  71.             Response r = ex.response;
  72.             throw new SensException("上传文件出错,请检查七牛云配置," + r.toString());
  73.         }
  74.     }
  75.     /**
  76.      * 文件流上传
  77.      * @param inputStream
  78.      * @param key  文件名
  79.      * @return
  80.      */
  81.     public String qiniuInputStreamUpload(InputStream inputStream, String key) {
  82.         OssSetting os = getOssSetting();
  83.         Auth auth = Auth.create(os.getAccessKey(), os.getSecretKey());
  84.         String upToken = auth.uploadToken(os.getBucket());
  85.         try {
  86.             Response response = getUploadManager(getConfiguration(os.getZone())).put(inputStream, key, upToken, nullnull);
  87.             DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
  88.             return os.getHttp() + os.getEndpoint() + "/" + putRet.key;
  89.         } catch (QiniuException ex) {
  90.             Response r = ex.response;
  91.             throw new SensException("上传文件出错,请检查七牛云配置," + r.toString());
  92.         }
  93.     }
  94.     /**
  95.      * 重命名
  96.      * @param fromKey
  97.      * @param toKey
  98.      */
  99.     public String renameFile(String fromKey, String toKey){
  100.         OssSetting os = getOssSetting();
  101.         Auth auth = Auth.create(os.getAccessKey(), os.getSecretKey());
  102.         BucketManager bucketManager = new BucketManager(auth, getConfiguration(os.getZone()));
  103.         try {
  104.             bucketManager.move(os.getBucket(), fromKey, os.getBucket(), toKey);
  105.             return os.getHttp() + os.getEndpoint() + "/" + toKey;
  106.         } catch (QiniuException ex) {
  107.             throw new SensException("重命名文件失败," + ex.response.toString());
  108.         }
  109.     }
  110.     /**
  111.      * 复制文件
  112.      * @param fromKey
  113.      */
  114.     public String copyFile(String fromKey, String toKey){
  115.         OssSetting os = getOssSetting();
  116.         Auth auth = Auth.create(os.getAccessKey(), os.getSecretKey());
  117.         BucketManager bucketManager = new BucketManager(auth, getConfiguration(os.getZone()));
  118.         try {
  119.             bucketManager.copy(os.getBucket(), fromKey, os.getBucket(), toKey);
  120.             return os.getHttp() + os.getEndpoint() + "/" + toKey;
  121.         } catch (QiniuException ex) {
  122.             throw new SensException("复制文件失败," + ex.response.toString());
  123.         }
  124.     }
  125.     /**
  126.      * 删除文件
  127.      * @param key
  128.      */
  129.     public void deleteFile(String key){
  130.         OssSetting os = getOssSetting();
  131.         Auth auth = Auth.create(os.getAccessKey(), os.getSecretKey());
  132.         BucketManager bucketManager = new BucketManager(auth, getConfiguration(os.getZone()));
  133.         try {
  134.             bucketManager.delete(os.getBucket(), key);
  135.         } catch (QiniuException ex) {
  136.             throw new SensException("删除文件失败," + ex.response.toString());
  137.         }
  138.     }
  139. }



② 阿里云 AliOssUtil.java
  1. package com.liuyanzhao.sens.common.utils;
  2. import com.liuyanzhao.sens.common.constant.SettingConstant;
  3. import com.liuyanzhao.sens.modules.base.vo.OssSetting;
  4. import com.liuyanzhao.sens.common.exception.SensException;
  5. import cn.hutool.core.util.StrUtil;
  6. import com.aliyun.oss.OSSClient;
  7. import com.google.gson.Gson;
  8. import lombok.extern.slf4j.Slf4j;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.data.redis.core.StringRedisTemplate;
  11. import org.springframework.stereotype.Component;
  12. import java.io.*;
  13. /**
  14.  * @author saysky
  15.  */
  16. @Component
  17. @Slf4j
  18. public class AliOssUtil {
  19.     @Autowired
  20.     private StringRedisTemplate redisTemplate;
  21.     public OssSetting getOssSetting(){
  22.         String v = redisTemplate.opsForValue().get(SettingConstant.ALI_OSS);
  23.         if(StrUtil.isBlank(v)){
  24.             throw new SensException("您还未配置阿里云OSS");
  25.         }
  26.         return new Gson().fromJson(v, OssSetting.class);
  27.     }
  28.     /**
  29.      * 文件路径上传
  30.      * @param filePath
  31.      * @param key
  32.      * @return
  33.      */
  34.     public String aliUpload(String filePath, String key) {
  35.         OssSetting os = getOssSetting();
  36.         OSSClient ossClient = new OSSClient(os.getHttp() + os.getEndpoint(), os.getAccessKey(), os.getSecretKey());
  37.         ossClient.putObject(os.getBucket(), key, new File(filePath));
  38.         ossClient.shutdown();
  39.         return os.getHttp() + os.getBucket() + "." + os.getEndpoint() + "/" + key;
  40.     }
  41.     /**
  42.      * 文件流上传
  43.      * @param inputStream
  44.      * @param key
  45.      * @return
  46.      */
  47.     public String aliInputStreamUpload(InputStream inputStream, String key) {
  48.         OssSetting os = getOssSetting();
  49.         OSSClient ossClient = new OSSClient(os.getHttp() + os.getEndpoint(), os.getAccessKey(), os.getSecretKey());
  50.         ossClient.putObject(os.getBucket(), key, inputStream);
  51.         ossClient.shutdown();
  52.         return os.getHttp() + os.getBucket() + "." + os.getEndpoint() + "/" + key;
  53.     }
  54.     /**
  55.      * 重命名
  56.      * @param fromKey
  57.      * @param toKey
  58.      */
  59.     public String renameFile(String fromKey, String toKey){
  60.         OssSetting os = getOssSetting();
  61.         copyFile(fromKey, toKey);
  62.         deleteFile(fromKey);
  63.         return os.getHttp() + os.getBucket() + "." + os.getEndpoint() + "/" + toKey;
  64.     }
  65.     /**
  66.      * 复制文件
  67.      * @param fromKey
  68.      */
  69.     public String copyFile(String fromKey, String toKey){
  70.         OssSetting os = getOssSetting();
  71.         OSSClient ossClient = new OSSClient(os.getHttp() + os.getEndpoint(), os.getAccessKey(), os.getSecretKey());
  72.         ossClient.copyObject(os.getBucket(), fromKey, os.getBucket(), toKey);
  73.         ossClient.shutdown();
  74.         return os.getHttp() + os.getBucket() + "." + os.getEndpoint() + "/" + toKey;
  75.     }
  76.     /**
  77.      * 删除文件
  78.      * @param key
  79.      */
  80.     public void deleteFile(String key){
  81.         OssSetting os = getOssSetting();
  82.         OSSClient ossClient = new OSSClient(os.getHttp() + os.getEndpoint(), os.getAccessKey(), os.getSecretKey());
  83.         ossClient.deleteObject(os.getBucket(), key);
  84.         ossClient.shutdown();
  85.     }
  86. }



③ 腾讯云 TencentOssUtil.java
  1. package com.liuyanzhao.sens.common.utils;
  2. import com.liuyanzhao.sens.common.constant.SettingConstant;
  3. import com.liuyanzhao.sens.modules.base.vo.OssSetting;
  4. import com.liuyanzhao.sens.common.exception.SensException;
  5. import cn.hutool.core.util.StrUtil;
  6. import com.google.gson.Gson;
  7. import com.qcloud.cos.COSClient;
  8. import com.qcloud.cos.ClientConfig;
  9. import com.qcloud.cos.auth.BasicCOSCredentials;
  10. import com.qcloud.cos.auth.COSCredentials;
  11. import com.qcloud.cos.model.*;
  12. import com.qcloud.cos.region.Region;
  13. import com.qcloud.cos.transfer.Copy;
  14. import com.qcloud.cos.transfer.TransferManager;
  15. import lombok.extern.slf4j.Slf4j;
  16. import org.springframework.beans.factory.annotation.Autowired;
  17. import org.springframework.data.redis.core.StringRedisTemplate;
  18. import org.springframework.stereotype.Component;
  19. import org.springframework.web.multipart.MultipartFile;
  20. import java.io.File;
  21. import java.io.InputStream;
  22. /**
  23.  * @author saysky
  24.  */
  25. @Component
  26. @Slf4j
  27. public class TencentOssUtil {
  28.     @Autowired
  29.     private StringRedisTemplate redisTemplate;
  30.     public OssSetting getOssSetting(){
  31.         String v = redisTemplate.opsForValue().get(SettingConstant.TENCENT_OSS);
  32.         if(StrUtil.isBlank(v)){
  33.             throw new SensException("您还未配置腾讯云COS");
  34.         }
  35.         return new Gson().fromJson(v, OssSetting.class);
  36.     }
  37.     /**
  38.      * 文件路径上传
  39.      * @param filePath
  40.      * @param key
  41.      * @return
  42.      */
  43.     public String tencentUpload(String filePath, String key) {
  44.         OssSetting os = getOssSetting();
  45.         COSCredentials cred = new BasicCOSCredentials(os.getAccessKey(), os.getSecretKey());
  46.         ClientConfig clientConfig = new ClientConfig(new Region(os.getBucketRegion()));
  47.         COSClient cosClient = new COSClient(cred, clientConfig);
  48.         PutObjectRequest putObjectRequest = new PutObjectRequest(os.getBucket(), key, new File(filePath));
  49.         PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
  50.         cosClient.shutdown();
  51.         return os.getHttp() + os.getEndpoint() + "/" + key;
  52.     }
  53.     /**
  54.      * 文件流上传
  55.      * 
  56.      * @param file 文件
  57.      * @param inputStream 输入流
  58.      * @param key 文件名
  59.      * @return
  60.      */
  61.     public String tencentInputStreamUpload(MultipartFile file, InputStream inputStream, String key) {
  62.         OssSetting os = getOssSetting();
  63.         COSCredentials cred = new BasicCOSCredentials(os.getAccessKey(), os.getSecretKey());
  64.         ClientConfig clientConfig = new ClientConfig(new Region(os.getBucketRegion()));
  65.         COSClient cosClient = new COSClient(cred, clientConfig);
  66.         ObjectMetadata objectMetadata = new ObjectMetadata();
  67.         objectMetadata.setContentLength(file.getSize());
  68.         objectMetadata.setContentType(file.getContentType());
  69.         PutObjectRequest putObjectRequest = new PutObjectRequest(os.getBucket(), key, inputStream, objectMetadata);
  70.         PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
  71.         cosClient.shutdown();
  72.         return os.getHttp() + os.getEndpoint() + "/" + key;
  73.     }
  74.     /**
  75.      * 重命名
  76.      * @param fromKey 原名
  77.      * @param toKey 目标名
  78.      */
  79.     public String renameFile(String fromKey, String toKey){
  80.         OssSetting os = getOssSetting();
  81.         copyFile(fromKey, toKey);
  82.         deleteFile(fromKey);
  83.         return os.getHttp() + os.getEndpoint() + "/" + toKey;
  84.     }
  85.     /**
  86.      * 复制文件
  87.      * 
  88.      * @param fromKey 原名
  89.      * @param fromKey 目标名
  90.      */
  91.     public String copyFile(String fromKey, String toKey){
  92.         OssSetting os = getOssSetting();
  93.         COSCredentials cred = new BasicCOSCredentials(os.getAccessKey(), os.getSecretKey());
  94.         ClientConfig clientConfig = new ClientConfig(new Region(os.getBucketRegion()));
  95.         COSClient cosClient = new COSClient(cred, clientConfig);
  96.         CopyObjectRequest copyObjectRequest = new CopyObjectRequest(os.getBucket(), fromKey, os.getBucket(), toKey);
  97.         TransferManager transferManager = new TransferManager(cosClient);
  98.         try {
  99.             Copy copy = transferManager.copy(copyObjectRequest, cosClient, null);
  100.             CopyResult copyResult = copy.waitForCopyResult();
  101.         } catch (Exception e) {
  102.             e.printStackTrace();
  103.             throw new SensException("复制文件失败");
  104.         }
  105.         transferManager.shutdownNow();
  106.         cosClient.shutdown();
  107.         return os.getHttp() + os.getEndpoint() + "/" + toKey;
  108.     }
  109.     /**
  110.      * 删除文件
  111.      * 
  112.      * @param key 原名
  113.      */
  114.     public void deleteFile(String key){
  115.         OssSetting os = getOssSetting();
  116.         COSCredentials cred = new BasicCOSCredentials(os.getAccessKey(), os.getSecretKey());
  117.         ClientConfig clientConfig = new ClientConfig(new Region(os.getBucketRegion()));
  118.         COSClient cosClient = new COSClient(cred, clientConfig);
  119.         cosClient.deleteObject(os.getBucket(), key);
  120.         cosClient.shutdown();
  121.     }
  122. }



④ 本地 FileUtil.java
  1. package com.liuyanzhao.sens.common.utils;
  2. import com.liuyanzhao.sens.common.constant.SettingConstant;
  3. import com.liuyanzhao.sens.modules.base.vo.OssSetting;
  4. import com.liuyanzhao.sens.common.exception.SensException;
  5. import cn.hutool.core.date.DateUtil;
  6. import cn.hutool.core.util.StrUtil;
  7. import com.google.gson.Gson;
  8. import lombok.extern.slf4j.Slf4j;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.data.redis.core.StringRedisTemplate;
  11. import org.springframework.stereotype.Component;
  12. import org.springframework.web.multipart.MultipartFile;
  13. import javax.servlet.http.HttpServletResponse;
  14. import java.io.*;
  15. /**
  16.  * @author saysky
  17.  */
  18. @Component
  19. @Slf4j
  20. public class FileUtil {
  21.     @Autowired
  22.     private StringRedisTemplate redisTemplate;
  23.     public OssSetting getOssSetting(){
  24.         String v = redisTemplate.opsForValue().get(SettingConstant.LOCAL_OSS);
  25.         if(StrUtil.isBlank(v)){
  26.             throw new SensException("您还未配置本地文件存储服务");
  27.         }
  28.         return new Gson().fromJson(v, OssSetting.class);
  29.     }
  30.     /**
  31.      * 文件路径上传
  32.      * @param file
  33.      * @param key
  34.      * @return
  35.      */
  36.     public String localUpload(MultipartFile file, String key) {
  37.         OssSetting os = getOssSetting();
  38.         String day = DateUtil.format(DateUtil.date(), "yyyyMMdd");
  39.         String path = os.getFilePath() + "/" + day;
  40.         File dir = new File(path);
  41.         if(!dir.exists()){
  42.             dir.mkdirs();
  43.         }
  44.         File f = new File(path + "/" + key);
  45.         if(f.exists()){
  46.             throw new SensException("文件名已存在");
  47.         }
  48.         try {
  49.             file.transferTo(f);
  50.             return path + "/" + key;
  51.         } catch (IOException e) {
  52.             log.error(e.toString());
  53.             throw new SensException("上传文件出错");
  54.         }
  55.     }
  56.     /**
  57.      * 读取文件
  58.      * @param url
  59.      * @param response
  60.      */
  61.     public void view(String url, HttpServletResponse response){
  62.         File file = new File(url);
  63.         FileInputStream i = null;
  64.         OutputStream o = null;
  65.         try {
  66.             i = new FileInputStream(file);
  67.             o = response.getOutputStream();
  68.             byte[] buf = new byte[1024];
  69.             int bytesRead;
  70.             while ((bytesRead = i.read(buf))>0){
  71.                 o.write(buf, 0, bytesRead);
  72.                 o.flush();
  73.             }
  74.             i.close();
  75.             o.close();
  76.         } catch (IOException e) {
  77.             log.error(e.toString());
  78.             throw new SensException("读取文件出错");
  79.         }
  80.     }
  81.     /**
  82.      * 重命名
  83.      * @param url
  84.      * @param toKey
  85.      * @return
  86.      */
  87.     public String renameFile(String url, String toKey){
  88.         String result = copyFile(url, toKey);
  89.         deleteFile(url);
  90.         return result;
  91.     }
  92.     /**
  93.      * 复制文件
  94.      * @param url
  95.      * @param toKey
  96.      */
  97.     public String copyFile(String url, String toKey){
  98.         File file = new File(url);
  99.         FileInputStream i = null;
  100.         FileOutputStream o = null;
  101.         try {
  102.             i = new FileInputStream(file);
  103.             o = new FileOutputStream(new File(file.getParentFile() + "/" + toKey));
  104.             byte[] buf = new byte[1024];
  105.             int bytesRead;
  106.             while ((bytesRead = i.read(buf))>0){
  107.                 o.write(buf, 0, bytesRead);
  108.             }
  109.             i.close();
  110.             o.close();
  111.             return file.getParentFile() + "/" + toKey;
  112.         } catch (IOException e) {
  113.             log.error(e.toString());
  114.             throw new SensException("复制文件出错");
  115.         }
  116.     }
  117.     /**
  118.      * 删除文件
  119.      * @param url
  120.      */
  121.     public void deleteFile(String url){
  122.         File file = new File(url);
  123.         file.delete();
  124.     }
  125. }



4.Maven依赖 pom.xml
  1. <!-- 七牛云SDK -->
  2. <dependency>
  3.     <groupId>com.qiniu</groupId>
  4.     <artifactId>qiniu-java-sdk</artifactId>
  5.     <version>[7.2.0, 7.2.99]</version>
  6. </dependency>
  7. <!-- 阿里云OSS -->
  8. <dependency>
  9.     <groupId>com.aliyun.oss</groupId>
  10.     <artifactId>aliyun-sdk-oss</artifactId>
  11.     <version>2.8.3</version>
  12. </dependency>
  13. <!-- 腾讯云COS -->
  14. <dependency>
  15.     <groupId>com.qcloud</groupId>
  16.     <artifactId>cos_api</artifactId>
  17.     <version>5.4.6</version>
  18. </dependency>
  19. <!-- Gson -->
  20. <dependency>
  21.     <groupId>com.google.code.gson</groupId>
  22.     <artifactId>gson</artifactId>
  23.     <version>2.8.5</version>
  24. </dependency>
  25. <!-- Hutool工具包 -->
  26. <dependency>
  27.     <groupId>cn.hutool</groupId>
  28.     <artifactId>hutool-all</artifactId>
  29.     <version>4.5.7</version>
  30. </dependency>
  31. <!-- Lombok -->
  32. <dependency>
  33.     <groupId>org.projectlombok</groupId>
  34.     <artifactId>lombok</artifactId>
  35.     <version>1.18.4</version>
  36. </dependency>


四、文末


前端这里就不贴了,毕竟大家都是后端开发。

有问题,可以在下方留言或者联系博主



官方文档

阿里云OSS上传文件

腾讯云COS上传文件

七牛云OSS上传文件
  • 微信
  • 交流学习,资料分享
  • weinxin
  • 个人淘宝
  • 店铺名:言曌博客咨询部

  • (部分商品未及时上架淘宝)

发表评论

avatar 登录者:匿名
匿名评论,评论回复后会有邮件通知

  

已通过评论:1   待审核评论数:0
  1. avatar 匿名

    啥年代了还用富文本,markdown不会吗?文字全部挤到一坨了 难看

    • avatar 言曌

      是不是 word 文档未来要被淘汰,全民使用命令来编辑文本?