注册七牛云 - 小王小王ii - 博客园 (cnblogs.com)
1.依赖
<dependencies><dependency><groupId>com.qiniu</groupId><artifactId>qiniu-java-sdk</artifactId><version>7.2.7</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.83</version></dependency> </dependencies>
2.文件工具类
package qiniu;public class FileUtil {// 图片允许的后缀扩展名public static String[] IMAGE_FILE_EXTD = new String[]{"png", "bmp", "jpg", "jpeg", "pdf"};/*** 获取文件后缀* @param fileName* @return*/public static String getSuffix(String fileName) {int i = fileName.lastIndexOf(".");//如果没有.证明该文件名不正确if (i < 0) {throw new RuntimeException("文件名不正确");};return fileName.substring(i + 1);}/*** 判断文件后缀是否符合规定* @param fileName* @return*/public static boolean isSuffixAllow(String fileName) {String suffix = FileUtil.getSuffix(fileName);for (String s : IMAGE_FILE_EXTD) {if (s.equals(suffix)) return true;}return false;} }
3.七牛云工具类
ak,ck在个人中心获取
外域链接在自己的bucket界面可以获取得到
package qiniu;import com.alibaba.fastjson.JSONObject; import com.qiniu.common.QiniuException; import com.qiniu.common.Zone; import com.qiniu.http.Response; import com.qiniu.storage.Configuration; import com.qiniu.storage.UploadManager; import com.qiniu.util.Auth;import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.UUID;public class QiNiuUtil {//以下信息在实际开发中应当从配置文件读取public static String ak = "?";public static String sk = "?";//外域链接public static String domainName = "?";/*** 上传文件* @param file 文件* @param bucketName* @return 返回URL,供访问(要公开的bucket才可以访问)*/public static String upload(File file, String bucketName) {//判断文件后缀是否符合规定if (!FileUtil.isSuffixAllow(file.getName())) {throw new RuntimeException("不支持改文件后缀");}try {FileInputStream fileInputStream = new FileInputStream(file);/*上传文件*///获取上传TokenAuth auth = Auth.create(ak, sk);String uploadToken = auth.uploadToken(bucketName);//构造文件名String fileName= UUID.randomUUID().toString().replace("-", "")+ "." + FileUtil.getSuffix(file.getName());//构造上传对象,上传文件UploadManager uploadManager = new UploadManager(new Configuration(Zone.zone2()));这里选择Zone1还是Zone2...要根据你选择的地区来定Response rep = uploadManager.put(fileInputStream, fileName, uploadToken, null, null);//构造访问URL进行返回return domainName + JSONObject.parseObject(rep.bodyString()).get("key").toString();} catch (FileNotFoundException e) {e.printStackTrace();throw new RuntimeException("上传文件失败");}catch (QiniuException e) {throw new RuntimeException("上传文件失败");}}public static void main(String[] args) {String upload = upload(new File("C:\\Users\\Administrator\\Desktop\\OIP-C.jpg"), "?");System.out.println(upload);} }