SpringBoot集成七牛云完成文件上传
进入七牛云(https://marketing.qiniu.com/)注册后进入--->个人中心--->密钥管理(如果没有就创建一个)
新建存储空间
新建存储空间后 空间名就是域名,点击域名就进入到域名链接
新建完一系列之后让我们动手敲代码吧!!!!
导入pom.xml
<!--七牛云--> <dependency> <groupId>com.qiniu</groupId> <artifactId>qiniu-java-sdk</artifactId> <version>7.2.11</version> </dependency>
配置yml
#七牛云配置
# 七牛密钥,配上自己申请的七牛账号对应的密钥
qiniu:
AccessKey:
SecretKey:
# 七牛空间名
Bucket:
BucketUrl:
简单文件上传
package com.yt.app.commons.utils; import com.google.gson.Gson; 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 org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.UUID; /** * @ClassName UploadFileUtil * @Description: 上传工具类 * @Author gzm * @Date 2020/5/14 16:54 **/ @Component public class UploadFileUtil { @Value("${qiNiuYun.AccessKey}") private String accessKey; @Value("${qiNiuYun.SecretKey}") private String secretKey; @Value("${qiNiuYun.Bucket}") private String bucket; @Value("${qiNiuYun.BucketUrl}") private String bucketUrl; /** * 在七牛云上保存文件 * 返回字符串 * * @param file * @return */ public String saveFile(MultipartFile file) throws IOException { //构造一个带指定Region对象的配置类 Configuration cfg = new Configuration(Region.huanan()); //生成上传凭证,然后准备上传 UploadManager uploadManager = new UploadManager(cfg); //创建权限类似于token Auth auth = Auth.create(accessKey,secretKey); //生成一个上传的token String upToken = auth.uploadToken(bucket); int pos = file.getOriginalFilename().lastIndexOf("."); if (pos<0) return null; //生存文件名 String fileExt = file.getOriginalFilename().substring(pos+1).toLowerCase(); String fileName = UUID.randomUUID().toString().replaceAll("-","")+"."+fileExt; try { Response response = uploadManager.put(file.getBytes(), fileName, upToken); //解析上传成功的结果 DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class); System.out.println(bucketUrl+putRet.key+"结果"); return bucketUrl+putRet.key; } catch (QiniuException ex) { Response r = ex.response; System.err.println(r.toString()); return null; } } public String getFileSuffix(String fileName) { //获取文件后缀名 return fileName.substring(fileName.lastIndexOf(".") + 1); } // private void checkSuffix(MultipartFile file) { // String suffix = getFileSuffix(file.getOriginalFilename()); // if (!Arrays.asList(allowSuffix).contains(suffix)) { // logger.error("不支持的文件类型"); // // throw new CustomRuntimeException(ResponseInfo.ResponseInfo_700.getCode().toString(), "不支持的文件类型"); // } // } }
注入bean以限制大小
package com.yt.xxx.app.config; import org.springframework.boot.web.servlet.MultipartConfigFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.servlet.MultipartConfigElement; /** * @ClassName UploadConfig * @Description: * @Author gzm * @Date 2020/6/4 16:24 **/ @Configuration public class UploadConfig { @Bean public MultipartConfigElement multipartConfigElement() { MultipartConfigFactory factory = new MultipartConfigFactory(); // 单个数据大小 factory.setMaxFileSize("2MB"); // KB,MB /// 总上传数据大小 factory.setMaxRequestSize("7MB"); return factory.createMultipartConfig(); } }
调用即可
package com.yt.xxx.app.controller; import com.yt.dzds.commons.model.pojo.LoginAppUser; import com.yt.dzds.commons.result.ResponseFailure; import com.yt.dzds.commons.result.ResponseInfo; import com.yt.dzds.commons.result.ResponseResult; import com.yt.dzds.commons.result.ResponseSuccess; import com.yt.dzds.commons.utils.AppUserUtil; import com.yt.dzds.commons.utils.FastUtils; import com.yt.dzds.commons.utils.StringUtils; import com.yt.dzds.commons.utils.UploadFileUtil; import com.yt.dzds.commons.utils.exception.NoAuthorityException; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; 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 java.io.IOException; /** * @ClassName Upload * @Description: * @Author gzm * @Date 2020/6/4 16:25 **/ @RestController @RequestMapping("upload") @Slf4j public class Upload { @Autowired private UploadFileUtil uploadFileUtil; @RequestMapping("files") public ResponseResult uploadFile(@RequestParam("file") MultipartFile file) throws IOException { //加入登录授权 LoginAppUser user = AppUserUtil.getLoginAppUser(); if(null==user){ FastUtils.checkCurrentUser(user); } long imgSize = file.getSize(); String suffix = uploadFileUtil.getFileSuffix(file.getOriginalFilename()); log.info("用户上传的图片信息:" + file.getOriginalFilename() + "( " + suffix + " )" + "( " + imgSize + "KB )"); // 上传的图片格式验证 // checkSuffix(file); String data = uploadFileUtil.saveFile(file); if (data != "") { return new ResponseSuccess<>(data); } else { return new ResponseFailure<>(ResponseInfo.ResponseInfo_610.getCode(), "保存错误"); } } }
大功告成,赶紧自己也去实现吧