七牛云文件上传
1、引入Maven依赖
<depende<dependency> <groupId>com.qiniu</groupId> <artifactId>qiniu-java-sdk</artifactId> <version>[7.7.0, 7.7.99]</version> </dependency>
2、配置yaml文件
qiniu: accessKey: xxx # 公钥 secretKey: xxx # 私钥 bucketName: ken-chy-blog #存储空间名称 path: http://cdn.ken-chy129.cn
公钥与私钥可以到密钥管理处查看
bucket为创建的对象存储的空间名称
path为文件管理中的外链域名(默认使用七牛云测试域名)
3、编写对应配置类
@org.springframework.context.annotation.Configuration public class UploadConfig { @Value("${qiniu.accessKey}") private String accessKey; @Value("${qiniu.secretKey}") private String secretKey; @Bean public Auth getAuth(){ return Auth.create(accessKey,secretKey); } @Bean public UploadManager getUploadManager(){ return new UploadManager(new Configuration()); } }
其中Auth.create()传入公钥私钥以创建权限,供UploadManager上传文件时使用
4、编写七牛云工具类
@Component public class QiniuUtils { @Autowired private UploadManager uploadManager; @Autowired private Auth auth; @Value("${qiniu.bucketName}") private String bucketName; @Value("${qiniu.path}") private String url; public String upload(FileInputStream file, String fileName) throws QiniuException { String token = auth.uploadToken(bucketName); Response res = uploadManager.put(file, fileName, token, null, null); if (!res.isOK()) { throw new RuntimeException("上传七牛云出错:" + res); } return url+"/"+fileName; } } @Compo
创建StringUtils工具类以生成图片名称
public class StringUtils { /** * @Description: 生成唯一图片名称 * @Param: fileName * @return: 云服务器fileName */ public static String getRandomImgName(String fileName) { int index = fileName.lastIndexOf("."); if (fileName.isEmpty() || index == -1){ throw new IllegalArgumentException(); } // 获取文件后缀 String suffix = fileName.substring(index).toLowerCase(); // 生成UUID String uuid = UUID.randomUUID().toString().replaceAll("-", ""); // 生成上传至云服务器的路径 return "userAvatar:" + uuid + suffix; } }
5、编写Service层
@Service public class PictureServiceImpl implements PictureService { @Autowired private QiniuUtils qiniuUtils; @Override public Result<String> upload(MultipartFile file) { if (file.isEmpty()) { return new Result<String>().failed(StatusCode.PICTURE_NULL); } String fileName = StringUtils.getRandomImgName(Objects.requireNonNull(file.getOriginalFilename())); try { FileInputStream uploadFile = (FileInputStream) file.getInputStream(); String path = qiniuUtils.upload(uploadFile, fileName); return new Result<String>().success(path); } catch (IOException e) { e.printStackTrace(); return new Result<String>().failed(StatusCode.ERROR); } } }
6、编写controller层
@RestController @CrossOrigin public class PictureController { @Autowired private PictureService pictureService; @PostMapping(value = "/upload") public Result<String> upload(@RequestParam("file") MultipartFile file) { return pictureService.upload(file); } }