一、依赖
首先我们引入七牛云SDK和Hutools依赖
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.5</version></dependency><dependency><groupId>com.qiniu</groupId><artifactId>qiniu-java-sdk</artifactId></dependency>
二、方法
/*** 获取上传凭证* @param accessKey 七牛云的accessKey * @param secretKey 七牛云的secretKey * @param bucket 七牛云的bucket*/public static String getUploadCredential(String accessKey, String secretKey,String bucket) {Auth auth = Auth.create(accessKey, secretKey);// System.out.println(upToken);return auth.uploadToken(bucket);}/*** 文件上传** @param zone 华东 Zone.zone0()* 华北 Zone.zone1()* 华南 Zone.zone2()* 北美 Zone.zoneNa0()* @param upToken 上传凭证* @param localFilePath 需要上传的文件本地路径*/public static DefaultPutRet fileUpload(Zone zone, String upToken, String localFilePath, String fileName) {// 构造一个带指定Zone对象的配置类Configuration cfg = new Configuration(zone);UploadManager uploadManager = new UploadManager(cfg);// 默认不指定key的情况下,以文件内容的hash值作为文件名try {Response response = uploadManager.put(localFilePath + fileName, fileName, upToken);// 解析上传成功的结果return new Gson().fromJson(response.bodyString(), DefaultPutRet.class);} catch (QiniuException ex) {Response r = ex.response;System.err.println(r.toString());try {System.err.println(r.bodyString());} catch (QiniuException ex2) {// ignore}}return null;}/*** @param filePath 文件路径* @param fileName 文件名称* @param fontUrl 上传位置* @return*/public static String fileUpload(String filePath, String fileName,String fontUrl) {DefaultPutRet defaultPutRet = fileUpload(Zone.zone2(), getUploadCredential(), filePath, fileName);if (defaultPutRet != null) {return fontUrl + defaultPutRet.key;}return "";}