因为博主之前七牛云被刷了波流量,损失惨重,目前不考虑使用七牛云了,会考虑阿里云、腾讯云和本地上传。
本文介绍 SpringBoot下,实现多种上传方式。
现在的设计是想在后台可以设置文件存储位置,支持动态切换。
界面如下,管理员在系统设置里可以选择系统文件上传位置。
实现思路,存储当前上传方式(本地,七牛云,阿里云,腾讯云),如选择了腾讯云,填好了bucket、地域、ak、sk、访问域名后,将该配置信息记录在redis中,当然也可以考虑持久化到 mysql 中。
当用户上传文件,如上传头像,调用上传通用接口,如 /upload/file 接口,在该方法内判断当前存储方式,查到是腾讯云,调用腾讯云的上传Service接口。
下面一一介绍这几种实现,只贴核心代码,有开发经验的朋友应该能直接看懂。
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
2.后台保存OSS配置接口 SettingController.java
OSS配置封装类 OssSetting.java
变量接口 SettingConstant.java
3.具体的上传实现接口
① 七牛云 QiniuUtil.java
② 阿里云 AliOssUtil.java
③ 腾讯云 TencentOssUtil.java
④ 本地 FileUtil.java
4.Maven依赖 pom.xml
前端这里就不贴了,毕竟大家都是后端开发。
有问题,可以在下方留言或者联系博主
官方文档
阿里云OSS上传文件
腾讯云COS上传文件
七牛云OSS上传文件
本文介绍 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
- package cn.exrick.xboot.modules.base.controller;
- import com.liuyanzhao.sens.common.constant.CommonConstant;
- importcom.liuyanzhao.sens.common.constant.SettingConstant;
- import com.liuyanzhao.senscommon.utils.*;
- import com.liuyanzhao.sens.common.vo.Result;
- import com.liuyanzhao.sens.modules.base.entity.File;
- import cn.hutool.core.util.StrUtil;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.redis.core.StringRedisTemplate;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- 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.InputStream;
- /**
- * @author saysky
- */
- @Slf4j
- @RestController
- @RequestMapping("/upload")
- public class UploadController {
- @Autowired
- private QiniuUtil qiniuUtil;
- @Autowired
- private AliOssUtil aliOssUtil;
- @Autowired
- private TencentOssUtil tencentOssUtil;
- @Autowired
- private FileUtil fileUtil;
- @Autowired
- private StringRedisTemplate redisTemplate;
- @RequestMapping(value = "/file", method = RequestMethod.POST)
- public Result<Object> upload(@RequestParam(required = false) MultipartFile file,
- @RequestParam(required = false) String base64,
- HttpServletRequest request) {
- String used = redisTemplate.opsForValue().get(SettingConstant.OSS_USED);
- if(StrUtil.isBlank(used)) {
- return new ResultUtil<Object>().setErrorMsg(501, "您还未配置OSS服务");
- }
- if(StrUtil.isNotBlank(base64)){
- // base64上传
- file = Base64DecodeMultipartFile.base64Convert(base64);
- }
- String result = "";
- //重命名文件,UUID+后缀
- String fKey = CommonUtil.renamePic(file.getOriginalFilename());
- File f = new File();
- try {
- InputStream inputStream = file.getInputStream();
- // 上传至第三方云服务或服务器
- if(used.equals(SettingConstant.QINIU_OSS)){
- //七牛云上传
- result = qiniuUtil.qiniuInputStreamUpload(inputStream, fKey);
- f.setLocation(CommonConstant.OSS_QINIU);
- }else if(used.equals(SettingConstant.ALI_OSS)){
- //阿里云上传
- result = aliOssUtil.aliInputStreamUpload(inputStream, fKey);
- f.setLocation(CommonConstant.OSS_ALI);
- }else if(used.equals(SettingConstant.TENCENT_OSS)){
- //腾讯云上传
- result = tencentOssUtil.tencentInputStreamUpload(file, inputStream, fKey);
- f.setLocation(CommonConstant.OSS_TENCENT);
- }else if(used.equals(SettingConstant.LOCAL_OSS)){
- //本地上传
- result = fileUtil.localUpload(file, fKey);
- f.setLocation(CommonConstant.OSS_LOCAL);
- }
- // 文件信息保存数据信息至数据库
- //略
- } catch (Exception e) {
- log.error(e.toString());
- return new ResultUtil<Object>().setErrorMsg(e.toString());
- }
- return new ResultUtil<Object>().setData(result);
- }
- }
2.后台保存OSS配置接口 SettingController.java
- @RequestMapping(value = "/oss/set", method = RequestMethod.POST)
- @ApiOperation(value = "OSS配置")
- public Result<Object> ossSet(@ModelAttribute OssSetting ossSetting) {
- if(ossSetting.getServiceName().equals(SettingConstant.QINIU_OSS)){
- // 七牛
- String v = redisTemplate.opsForValue().get(SettingConstant.QINIU_OSS);
- if(StrUtil.isNotBlank(v)&&!ossSetting.getChanged()){
- String secrectKey = new Gson().fromJson(v, OssSetting.class).getSecretKey();
- ossSetting.setSecretKey(secrectKey);
- }
- redisTemplate.opsForValue().set(SettingConstant.QINIU_OSS, new Gson().toJson(ossSetting));
- redisTemplate.opsForValue().set(SettingConstant.OSS_USED, SettingConstant.QINIU_OSS);
- }else if(ossSetting.getServiceName().equals(SettingConstant.ALI_OSS)){
- // 阿里
- String v = redisTemplate.opsForValue().get(SettingConstant.ALI_OSS);
- if(StrUtil.isNotBlank(v)&&!ossSetting.getChanged()){
- String secrectKey = new Gson().fromJson(v, OssSetting.class).getSecretKey();
- ossSetting.setSecretKey(secrectKey);
- }
- redisTemplate.opsForValue().set(SettingConstant.ALI_OSS, new Gson().toJson(ossSetting));
- redisTemplate.opsForValue().set(SettingConstant.OSS_USED, SettingConstant.ALI_OSS);
- }else if(ossSetting.getServiceName().equals(SettingConstant.TENCENT_OSS)){
- // 腾讯
- String v = redisTemplate.opsForValue().get(SettingConstant.TENCENT_OSS);
- if(StrUtil.isNotBlank(v)&&!ossSetting.getChanged()){
- String secrectKey = new Gson().fromJson(v, OssSetting.class).getSecretKey();
- ossSetting.setSecretKey(secrectKey);
- }
- redisTemplate.opsForValue().set(SettingConstant.TENCENT_OSS, new Gson().toJson(ossSetting));
- redisTemplate.opsForValue().set(SettingConstant.OSS_USED, SettingConstant.TENCENT_OSS);
- }else if(ossSetting.getServiceName().equals(SettingConstant.LOCAL_OSS)){
- // 本地
- redisTemplate.opsForValue().set(SettingConstant.LOCAL_OSS, new Gson().toJson(ossSetting));
- redisTemplate.opsForValue().set(SettingConstant.OSS_USED, SettingConstant.LOCAL_OSS);
- }
- return new ResultUtil<Object>().setData(null);
- }
OSS配置封装类 OssSetting.java
- package com.liuyanzhao.sens.modules.base.vo;
- import lombok.Data;
- import java.io.Serializable;
- /**
- * @author saysky
- */
- @Data
- public class OssSetting implements Serializable{
- private String serviceName;
- private String accessKey;
- private String secretKey;
- private String endpoint;
- private String bucket;
- private String http;
- private Integer zone;
- private String bucketRegion;
- private String filePath;
- private Boolean changed;
- }
变量接口 SettingConstant.java
- package com.liuyanzhao.sens.common.constant;
- /**
- * @author saysky
- */
- public interface SettingConstant {
- /**
- * 当前使用OSS
- */
- String OSS_USED = "OSS_USED";
- /**
- * 七牛OSS配置
- */
- String QINIU_OSS = "QINIU_OSS";
- /**
- * 七牛云存储区域 自动判断
- */
- Integer ZONE_AUTO = -1;
- /**
- * 七牛云存储区域 华东
- */
- Integer ZONE_ZERO = 0;
- /**
- * 七牛云存储区域 华北
- */
- Integer ZONE_ONE = 1;
- /**
- * 七牛云存储区域 华南
- */
- Integer ZONE_TWO = 2;
- /**
- * 七牛云存储区域 北美
- */
- Integer ZONE_THREE = 3;
- /**
- * 七牛云存储区域 东南亚
- */
- Integer ZONE_FOUR = 4;
- /**
- * 阿里OSS配置
- */
- String ALI_OSS = "ALI_OSS";
- /**
- * 腾讯COS配置
- */
- String TENCENT_OSS = "TENCENT_OSS";
- /**
- * 本地OSS配置
- */
- String LOCAL_OSS = "LOCAL_OSS";
- }
3.具体的上传实现接口
① 七牛云 QiniuUtil.java
- package com.liuyanzhao.sens.common.utils;
- import com.liuyanzhao.sens.common.constant.SettingConstant;
- import com.liuyanzhao.sens.modules.base.vo.OssSetting;
- import com.liuyanzhao.sens.common.exception.SensException;
- import cn.hutool.core.util.StrUtil;
- import com.google.gson.Gson;
- import com.qiniu.common.QiniuException;
- import com.qiniu.common.Zone;
- import com.qiniu.http.Response;
- import com.qiniu.storage.BucketManager;
- import com.qiniu.storage.Configuration;
- import com.qiniu.storage.UploadManager;
- import com.qiniu.storage.model.DefaultPutRet;
- import com.qiniu.util.Auth;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.redis.core.StringRedisTemplate;
- import org.springframework.stereotype.Component;
- import java.io.InputStream;
- /**
- * @author saysky
- */
- @Slf4j
- @Component
- public class QiniuUtil {
- @Autowired
- private StringRedisTemplate redisTemplate;
- public OssSetting getOssSetting(){
- String v = redisTemplate.opsForValue().get(SettingConstant.QINIU_OSS);
- if(StrUtil.isBlank(v)){
- throw new SensException("您还未配置七牛云OSS");
- }
- return new Gson().fromJson(v, OssSetting.class);
- }
- public Configuration getConfiguration(Integer zone){
- Configuration cfg = null;
- if(zone.equals(SettingConstant.ZONE_ZERO)){
- cfg = new Configuration(Zone.zone0());
- }else if(zone.equals(SettingConstant.ZONE_ONE)){
- cfg = new Configuration(Zone.zone1());
- }else if(zone.equals(SettingConstant.ZONE_TWO)){
- cfg = new Configuration(Zone.zone2());
- }else if(zone.equals(SettingConstant.ZONE_THREE)){
- cfg = new Configuration(Zone.zoneNa0());
- }else if(zone.equals(SettingConstant.ZONE_FOUR)){
- cfg = new Configuration(Zone.zoneAs0());
- }else {
- cfg = new Configuration(Zone.autoZone());
- }
- return cfg;
- }
- public UploadManager getUploadManager(Configuration cfg){
- UploadManager uploadManager = new UploadManager(cfg);
- return uploadManager;
- }
- /**
- * 文件路径上传
- * @param filePath
- * @param key 文件名
- * @return
- */
- public String qiniuUpload(String filePath, String key) {
- OssSetting os = getOssSetting();
- Auth auth = Auth.create(os.getAccessKey(), os.getSecretKey());
- String upToken = auth.uploadToken(os.getBucket());
- try {
- Response response = getUploadManager(getConfiguration(os.getZone())).put(filePath, key, upToken);
- DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
- return os.getHttp() + os.getEndpoint() + "/" + putRet.key;
- } catch (QiniuException ex) {
- Response r = ex.response;
- throw new SensException("上传文件出错,请检查七牛云配置," + r.toString());
- }
- }
- /**
- * 文件流上传
- * @param inputStream
- * @param key 文件名
- * @return
- */
- public String qiniuInputStreamUpload(InputStream inputStream, String key) {
- OssSetting os = getOssSetting();
- Auth auth = Auth.create(os.getAccessKey(), os.getSecretKey());
- String upToken = auth.uploadToken(os.getBucket());
- try {
- Response response = getUploadManager(getConfiguration(os.getZone())).put(inputStream, key, upToken, null, null);
- DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
- return os.getHttp() + os.getEndpoint() + "/" + putRet.key;
- } catch (QiniuException ex) {
- Response r = ex.response;
- throw new SensException("上传文件出错,请检查七牛云配置," + r.toString());
- }
- }
- /**
- * 重命名
- * @param fromKey
- * @param toKey
- */
- public String renameFile(String fromKey, String toKey){
- OssSetting os = getOssSetting();
- Auth auth = Auth.create(os.getAccessKey(), os.getSecretKey());
- BucketManager bucketManager = new BucketManager(auth, getConfiguration(os.getZone()));
- try {
- bucketManager.move(os.getBucket(), fromKey, os.getBucket(), toKey);
- return os.getHttp() + os.getEndpoint() + "/" + toKey;
- } catch (QiniuException ex) {
- throw new SensException("重命名文件失败," + ex.response.toString());
- }
- }
- /**
- * 复制文件
- * @param fromKey
- */
- public String copyFile(String fromKey, String toKey){
- OssSetting os = getOssSetting();
- Auth auth = Auth.create(os.getAccessKey(), os.getSecretKey());
- BucketManager bucketManager = new BucketManager(auth, getConfiguration(os.getZone()));
- try {
- bucketManager.copy(os.getBucket(), fromKey, os.getBucket(), toKey);
- return os.getHttp() + os.getEndpoint() + "/" + toKey;
- } catch (QiniuException ex) {
- throw new SensException("复制文件失败," + ex.response.toString());
- }
- }
- /**
- * 删除文件
- * @param key
- */
- public void deleteFile(String key){
- OssSetting os = getOssSetting();
- Auth auth = Auth.create(os.getAccessKey(), os.getSecretKey());
- BucketManager bucketManager = new BucketManager(auth, getConfiguration(os.getZone()));
- try {
- bucketManager.delete(os.getBucket(), key);
- } catch (QiniuException ex) {
- throw new SensException("删除文件失败," + ex.response.toString());
- }
- }
- }
② 阿里云 AliOssUtil.java
- package com.liuyanzhao.sens.common.utils;
- import com.liuyanzhao.sens.common.constant.SettingConstant;
- import com.liuyanzhao.sens.modules.base.vo.OssSetting;
- import com.liuyanzhao.sens.common.exception.SensException;
- import cn.hutool.core.util.StrUtil;
- import com.aliyun.oss.OSSClient;
- import com.google.gson.Gson;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.redis.core.StringRedisTemplate;
- import org.springframework.stereotype.Component;
- import java.io.*;
- /**
- * @author saysky
- */
- @Component
- @Slf4j
- public class AliOssUtil {
- @Autowired
- private StringRedisTemplate redisTemplate;
- public OssSetting getOssSetting(){
- String v = redisTemplate.opsForValue().get(SettingConstant.ALI_OSS);
- if(StrUtil.isBlank(v)){
- throw new SensException("您还未配置阿里云OSS");
- }
- return new Gson().fromJson(v, OssSetting.class);
- }
- /**
- * 文件路径上传
- * @param filePath
- * @param key
- * @return
- */
- public String aliUpload(String filePath, String key) {
- OssSetting os = getOssSetting();
- OSSClient ossClient = new OSSClient(os.getHttp() + os.getEndpoint(), os.getAccessKey(), os.getSecretKey());
- ossClient.putObject(os.getBucket(), key, new File(filePath));
- ossClient.shutdown();
- return os.getHttp() + os.getBucket() + "." + os.getEndpoint() + "/" + key;
- }
- /**
- * 文件流上传
- * @param inputStream
- * @param key
- * @return
- */
- public String aliInputStreamUpload(InputStream inputStream, String key) {
- OssSetting os = getOssSetting();
- OSSClient ossClient = new OSSClient(os.getHttp() + os.getEndpoint(), os.getAccessKey(), os.getSecretKey());
- ossClient.putObject(os.getBucket(), key, inputStream);
- ossClient.shutdown();
- return os.getHttp() + os.getBucket() + "." + os.getEndpoint() + "/" + key;
- }
- /**
- * 重命名
- * @param fromKey
- * @param toKey
- */
- public String renameFile(String fromKey, String toKey){
- OssSetting os = getOssSetting();
- copyFile(fromKey, toKey);
- deleteFile(fromKey);
- return os.getHttp() + os.getBucket() + "." + os.getEndpoint() + "/" + toKey;
- }
- /**
- * 复制文件
- * @param fromKey
- */
- public String copyFile(String fromKey, String toKey){
- OssSetting os = getOssSetting();
- OSSClient ossClient = new OSSClient(os.getHttp() + os.getEndpoint(), os.getAccessKey(), os.getSecretKey());
- ossClient.copyObject(os.getBucket(), fromKey, os.getBucket(), toKey);
- ossClient.shutdown();
- return os.getHttp() + os.getBucket() + "." + os.getEndpoint() + "/" + toKey;
- }
- /**
- * 删除文件
- * @param key
- */
- public void deleteFile(String key){
- OssSetting os = getOssSetting();
- OSSClient ossClient = new OSSClient(os.getHttp() + os.getEndpoint(), os.getAccessKey(), os.getSecretKey());
- ossClient.deleteObject(os.getBucket(), key);
- ossClient.shutdown();
- }
- }
③ 腾讯云 TencentOssUtil.java
- package com.liuyanzhao.sens.common.utils;
- import com.liuyanzhao.sens.common.constant.SettingConstant;
- import com.liuyanzhao.sens.modules.base.vo.OssSetting;
- import com.liuyanzhao.sens.common.exception.SensException;
- import cn.hutool.core.util.StrUtil;
- import com.google.gson.Gson;
- import com.qcloud.cos.COSClient;
- import com.qcloud.cos.ClientConfig;
- import com.qcloud.cos.auth.BasicCOSCredentials;
- import com.qcloud.cos.auth.COSCredentials;
- import com.qcloud.cos.model.*;
- import com.qcloud.cos.region.Region;
- import com.qcloud.cos.transfer.Copy;
- import com.qcloud.cos.transfer.TransferManager;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.redis.core.StringRedisTemplate;
- import org.springframework.stereotype.Component;
- import org.springframework.web.multipart.MultipartFile;
- import java.io.File;
- import java.io.InputStream;
- /**
- * @author saysky
- */
- @Component
- @Slf4j
- public class TencentOssUtil {
- @Autowired
- private StringRedisTemplate redisTemplate;
- public OssSetting getOssSetting(){
- String v = redisTemplate.opsForValue().get(SettingConstant.TENCENT_OSS);
- if(StrUtil.isBlank(v)){
- throw new SensException("您还未配置腾讯云COS");
- }
- return new Gson().fromJson(v, OssSetting.class);
- }
- /**
- * 文件路径上传
- * @param filePath
- * @param key
- * @return
- */
- public String tencentUpload(String filePath, String key) {
- OssSetting os = getOssSetting();
- COSCredentials cred = new BasicCOSCredentials(os.getAccessKey(), os.getSecretKey());
- ClientConfig clientConfig = new ClientConfig(new Region(os.getBucketRegion()));
- COSClient cosClient = new COSClient(cred, clientConfig);
- PutObjectRequest putObjectRequest = new PutObjectRequest(os.getBucket(), key, new File(filePath));
- PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
- cosClient.shutdown();
- return os.getHttp() + os.getEndpoint() + "/" + key;
- }
- /**
- * 文件流上传
- *
- * @param file 文件
- * @param inputStream 输入流
- * @param key 文件名
- * @return
- */
- public String tencentInputStreamUpload(MultipartFile file, InputStream inputStream, String key) {
- OssSetting os = getOssSetting();
- COSCredentials cred = new BasicCOSCredentials(os.getAccessKey(), os.getSecretKey());
- ClientConfig clientConfig = new ClientConfig(new Region(os.getBucketRegion()));
- COSClient cosClient = new COSClient(cred, clientConfig);
- ObjectMetadata objectMetadata = new ObjectMetadata();
- objectMetadata.setContentLength(file.getSize());
- objectMetadata.setContentType(file.getContentType());
- PutObjectRequest putObjectRequest = new PutObjectRequest(os.getBucket(), key, inputStream, objectMetadata);
- PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
- cosClient.shutdown();
- return os.getHttp() + os.getEndpoint() + "/" + key;
- }
- /**
- * 重命名
- * @param fromKey 原名
- * @param toKey 目标名
- */
- public String renameFile(String fromKey, String toKey){
- OssSetting os = getOssSetting();
- copyFile(fromKey, toKey);
- deleteFile(fromKey);
- return os.getHttp() + os.getEndpoint() + "/" + toKey;
- }
- /**
- * 复制文件
- *
- * @param fromKey 原名
- * @param fromKey 目标名
- */
- public String copyFile(String fromKey, String toKey){
- OssSetting os = getOssSetting();
- COSCredentials cred = new BasicCOSCredentials(os.getAccessKey(), os.getSecretKey());
- ClientConfig clientConfig = new ClientConfig(new Region(os.getBucketRegion()));
- COSClient cosClient = new COSClient(cred, clientConfig);
- CopyObjectRequest copyObjectRequest = new CopyObjectRequest(os.getBucket(), fromKey, os.getBucket(), toKey);
- TransferManager transferManager = new TransferManager(cosClient);
- try {
- Copy copy = transferManager.copy(copyObjectRequest, cosClient, null);
- CopyResult copyResult = copy.waitForCopyResult();
- } catch (Exception e) {
- e.printStackTrace();
- throw new SensException("复制文件失败");
- }
- transferManager.shutdownNow();
- cosClient.shutdown();
- return os.getHttp() + os.getEndpoint() + "/" + toKey;
- }
- /**
- * 删除文件
- *
- * @param key 原名
- */
- public void deleteFile(String key){
- OssSetting os = getOssSetting();
- COSCredentials cred = new BasicCOSCredentials(os.getAccessKey(), os.getSecretKey());
- ClientConfig clientConfig = new ClientConfig(new Region(os.getBucketRegion()));
- COSClient cosClient = new COSClient(cred, clientConfig);
- cosClient.deleteObject(os.getBucket(), key);
- cosClient.shutdown();
- }
- }
④ 本地 FileUtil.java
- package com.liuyanzhao.sens.common.utils;
- import com.liuyanzhao.sens.common.constant.SettingConstant;
- import com.liuyanzhao.sens.modules.base.vo.OssSetting;
- import com.liuyanzhao.sens.common.exception.SensException;
- import cn.hutool.core.date.DateUtil;
- import cn.hutool.core.util.StrUtil;
- import com.google.gson.Gson;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.redis.core.StringRedisTemplate;
- import org.springframework.stereotype.Component;
- import org.springframework.web.multipart.MultipartFile;
- import javax.servlet.http.HttpServletResponse;
- import java.io.*;
- /**
- * @author saysky
- */
- @Component
- @Slf4j
- public class FileUtil {
- @Autowired
- private StringRedisTemplate redisTemplate;
- public OssSetting getOssSetting(){
- String v = redisTemplate.opsForValue().get(SettingConstant.LOCAL_OSS);
- if(StrUtil.isBlank(v)){
- throw new SensException("您还未配置本地文件存储服务");
- }
- return new Gson().fromJson(v, OssSetting.class);
- }
- /**
- * 文件路径上传
- * @param file
- * @param key
- * @return
- */
- public String localUpload(MultipartFile file, String key) {
- OssSetting os = getOssSetting();
- String day = DateUtil.format(DateUtil.date(), "yyyyMMdd");
- String path = os.getFilePath() + "/" + day;
- File dir = new File(path);
- if(!dir.exists()){
- dir.mkdirs();
- }
- File f = new File(path + "/" + key);
- if(f.exists()){
- throw new SensException("文件名已存在");
- }
- try {
- file.transferTo(f);
- return path + "/" + key;
- } catch (IOException e) {
- log.error(e.toString());
- throw new SensException("上传文件出错");
- }
- }
- /**
- * 读取文件
- * @param url
- * @param response
- */
- public void view(String url, HttpServletResponse response){
- File file = new File(url);
- FileInputStream i = null;
- OutputStream o = null;
- try {
- i = new FileInputStream(file);
- o = response.getOutputStream();
- byte[] buf = new byte[1024];
- int bytesRead;
- while ((bytesRead = i.read(buf))>0){
- o.write(buf, 0, bytesRead);
- o.flush();
- }
- i.close();
- o.close();
- } catch (IOException e) {
- log.error(e.toString());
- throw new SensException("读取文件出错");
- }
- }
- /**
- * 重命名
- * @param url
- * @param toKey
- * @return
- */
- public String renameFile(String url, String toKey){
- String result = copyFile(url, toKey);
- deleteFile(url);
- return result;
- }
- /**
- * 复制文件
- * @param url
- * @param toKey
- */
- public String copyFile(String url, String toKey){
- File file = new File(url);
- FileInputStream i = null;
- FileOutputStream o = null;
- try {
- i = new FileInputStream(file);
- o = new FileOutputStream(new File(file.getParentFile() + "/" + toKey));
- byte[] buf = new byte[1024];
- int bytesRead;
- while ((bytesRead = i.read(buf))>0){
- o.write(buf, 0, bytesRead);
- }
- i.close();
- o.close();
- return file.getParentFile() + "/" + toKey;
- } catch (IOException e) {
- log.error(e.toString());
- throw new SensException("复制文件出错");
- }
- }
- /**
- * 删除文件
- * @param url
- */
- public void deleteFile(String url){
- File file = new File(url);
- file.delete();
- }
- }
4.Maven依赖 pom.xml
- <!-- 七牛云SDK -->
- <dependency>
- <groupId>com.qiniu</groupId>
- <artifactId>qiniu-java-sdk</artifactId>
- <version>[7.2.0, 7.2.99]</version>
- </dependency>
- <!-- 阿里云OSS -->
- <dependency>
- <groupId>com.aliyun.oss</groupId>
- <artifactId>aliyun-sdk-oss</artifactId>
- <version>2.8.3</version>
- </dependency>
- <!-- 腾讯云COS -->
- <dependency>
- <groupId>com.qcloud</groupId>
- <artifactId>cos_api</artifactId>
- <version>5.4.6</version>
- </dependency>
- <!-- Gson -->
- <dependency>
- <groupId>com.google.code.gson</groupId>
- <artifactId>gson</artifactId>
- <version>2.8.5</version>
- </dependency>
- <!-- Hutool工具包 -->
- <dependency>
- <groupId>cn.hutool</groupId>
- <artifactId>hutool-all</artifactId>
- <version>4.5.7</version>
- </dependency>
- <!-- Lombok -->
- <dependency>
- <groupId>org.projectlombok</groupId>
- <artifactId>lombok</artifactId>
- <version>1.18.4</version>
- </dependency>
四、文末
前端这里就不贴了,毕竟大家都是后端开发。
有问题,可以在下方留言或者联系博主
官方文档
阿里云OSS上传文件
腾讯云COS上传文件
七牛云OSS上传文件
2020年04月18日 11:54:48
啥年代了还用富文本,markdown不会吗?文字全部挤到一坨了 难看
2020年05月02日 13:09:22
是不是 word 文档未来要被淘汰,全民使用命令来编辑文本?