调用测试
package com.example.honyee;
import com.example.honyee.qiniu.QiniuUtils;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
public class QiniuTest {
static String rootPath = "C:\\Users\\Lenovo\\Desktop\\xiuxian-data-station\\xiuxian-v3.5\\";
public static void main(String[] args) throws IOException {
upload(new File(rootPath));
}
public static void upload(File file) throws IOException {
if (file == null || !file.exists()) {
return;
}
if (file.isFile()) {
byte[] bytes = Files.readAllBytes(Path.of(file.getPath()));
String key = file.getAbsolutePath().replace(rootPath, "").replaceAll("\\\\","/");
String resKey = QiniuUtils.uploadImage(bytes, key);
System.out.println(key);
} else {
for (File child : Optional.ofNullable(file.listFiles()).orElse(new File[]{})) {
upload(child);
}
}
}
}
目录结构

maven
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.7.0, 7.10.99]</version>
</dependency>
工具封装
QiniuUtils
package com.example.honyee.qiniu;
import com.example.honyee.qiniu.base.QiniuAuditCallbackV2;
import com.example.honyee.qiniu.base.QiniuBase;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qiniu.storage.Region;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
public class QiniuUtils {
private static final Logger logger = LoggerFactory.getLogger(QiniuUtils.class);
public static final String AK = "VQlK3dF5dbJwxrMH04DHXt6A9Gt5LmChYimT_1Vb";
public static final String SK = "rXxxXElw15v2eeDzFhIvw2zEhpOF0gcT6wXMv8uD";
public static final String BUCKET_NAME = "lanren-station";
public static final String BASE_URL = "";
public static final Region REGION = Region.regionCnEast2();
public static final Auth AUTH = Auth.create(AK, SK);
public static String getUpToken() {
return AUTH.uploadToken(BUCKET_NAME);
}
public static String uploadImage(MultipartFile file, String key) {
try {
return QiniuBase.uploadImage(file.getBytes(), key, getUpToken(), REGION);
} catch (IOException e) {
logger.info("七牛图片上传失败,IO错误{}", e.getMessage());
}
return null;
}
public static String uploadImage(byte[] bytes, String key) {
return QiniuBase.uploadImage(bytes, key, getUpToken(), REGION);
}
public static String uploadImage(byte[] bytes, String type, String userId, String key) {
return uploadImage(bytes, String.format("%s/%s/%s", type, userId, key));
}
public static String uploadImage(MultipartFile file, String type, String userId, String key) {
return uploadImage(file, String.format("%s/%s/%s", type, userId, key));
}
public static boolean deleteImage(String key) {
return QiniuBase.deleteImage(key, BUCKET_NAME, REGION, AUTH);
}
public static boolean exists(String key) {
if (key.charAt(0) == '/') {
key = key.substring(1);
}
return QiniuBase.exists(key, BUCKET_NAME, REGION, AUTH);
}
public static boolean refresh(String filePath) {
return QiniuBase.refresh(BASE_URL + filePath, AUTH);
}
public static boolean auditImageYellow(String imageName) throws JsonProcessingException {
if(imageName == null){
return false;
}
String url = BASE_URL + imageName;
String result = QiniuBase.imgAuditYellow(AUTH, url);
QiniuAuditCallbackV2 callbackV2 = new ObjectMapper().readValue(result, QiniuAuditCallbackV2.class);
if(callbackV2 != null && callbackV2.isAuditPass()) {
return callbackV2.isBlock();
}
logger.error("鉴黄异常:{}", result);
return false;
}
public static boolean auditImageAdvertisement(String imageName) throws JsonProcessingException {
if (imageName == null) {
return false;
}
String url = BASE_URL + imageName;
String result = QiniuBase.imgAuditAdvertisement(AUTH, url);
QiniuAuditCallbackV2 callbackV2 = new ObjectMapper().readValue(result, QiniuAuditCallbackV2.class);
if (callbackV2 != null && callbackV2.isAuditPass()) {
boolean b = callbackV2.isBlock() || callbackV2.isReview();
if (b) {
logger.error("广告图片:{}", imageName);
}
return b;
}
logger.error("鉴黄异常:{}", result);
return false;
}
public static boolean uploadWithAudit(MultipartFile file,String key) throws JsonProcessingException {
String fileName = uploadImage(file, key);
return audit(fileName);
}
public static boolean audit(String fileName) throws JsonProcessingException {
return auditImageYellow(fileName) || auditImageAdvertisement(fileName);
}
public static boolean uploadWithAudit(byte[] fileBytes,String key) throws JsonProcessingException {
return auditImageYellow(uploadImage(fileBytes, key));
}
}
QiniuBase
package com.example.honyee.qiniu.base;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qiniu.cdn.CdnManager;
import com.qiniu.cdn.CdnResult;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Client;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
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 com.qiniu.util.StringMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream;
public class QiniuBase {
private static final Logger logger = LoggerFactory.getLogger(QiniuBase.class);
public static final String AUDIT_PARAM = "?qpulp";
public static String uploadImage(byte[] uploadBytes, String key, String upToken, Region region) {
Configuration cfg = new Configuration(region);
UploadManager uploadManager = new UploadManager(cfg);
try {
if (key.charAt(0) == '/') {
key = key.substring(1);
}
ByteArrayInputStream byteInputStream = new ByteArrayInputStream(uploadBytes);
Response response = uploadManager.put(byteInputStream, key, upToken, null, null);
DefaultPutRet putRet = new ObjectMapper().readValue(response.bodyString(), DefaultPutRet.class);
return putRet.key;
} catch (QiniuException ex) {
Response r = ex.response;
logger.info("七牛图片上传错误,{}", r.toString());
try {
logger.info("七牛图片上传错误,{}", r.bodyString());
} catch (QiniuException ex2) {
}
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
return key;
}
public static boolean deleteImage(String key, String bucket, Region region, Auth auth) {
Configuration cfg = new Configuration(region);
BucketManager bucketManager = new BucketManager(auth, cfg);
try {
if (key.charAt(0) == '/') {
key = key.substring(1);
}
bucketManager.delete(bucket, key);
} catch (QiniuException ex) {
logger.info(ex.code() + "");
logger.info(ex.response.toString());
return false;
}
return true;
}
public static boolean exists(String key, String bucket, Region region, Auth auth) {
Configuration cfg = new Configuration(region);
BucketManager bucketManager = new BucketManager(auth, cfg);
try {
if (key.charAt(0) == '/') {
key = key.substring(1);
}
bucketManager.stat(bucket, key);
} catch (QiniuException ex) {
return false;
}
return true;
}
public static boolean refresh(String url, Auth auth) {
CdnManager c = new CdnManager(auth);
String[] urls = new String[]{
url
};
try {
CdnResult.RefreshResult result = c.refreshUrls(urls);
System.out.println(result.code);
} catch (QiniuException e) {
System.err.println(e.response.toString());
return false;
}
return true;
}
public static String imgAuditYellow(Auth auth, String url) {
String requestUrl = "http://ai.qiniuapi.com/v3/image/censor";
String host = "ai.qiniuapi.com";
String body = "{ \"data\": { \"uri\": \"" + url + "\" }, \"params\": { \"scenes\": [ \"pulp\" ] } }";
String contentType = "application/json";
String method = "POST";
String qiniuToken = "Qiniu " + auth.signRequestV2(requestUrl, method, body.getBytes(), contentType);
StringMap header = new StringMap();
header.put("Host", host);
header.put("Authorization", qiniuToken);
header.put("Content-Type", contentType);
Configuration cfg = new Configuration(Region.autoRegion());
Client client = new Client(cfg);
Response response = null;
try {
response = client.post(requestUrl, body.getBytes(), header, contentType);
return response.bodyString();
} catch (QiniuException e) {
e.printStackTrace();
return null;
}
}
public static String imgAuditAdvertisement(Auth auth, String url) {
String requestUrl = "http://ai.qiniuapi.com/v3/image/censor";
String host = "ai.qiniuapi.com";
String body = "{ \"data\": { \"uri\": \"" + url + "\" }, \"params\": { \"scenes\": [ \"ads\" ] } }";
String contentType = "application/json";
String method = "POST";
String qiniuToken = "Qiniu " + auth.signRequestV2(requestUrl, method, body.getBytes(), contentType);
StringMap header = new StringMap();
header.put("Host", host);
header.put("Authorization", qiniuToken);
header.put("Content-Type", contentType);
Configuration cfg = new Configuration(Region.autoRegion());
Client client = new Client(cfg);
Response response = null;
try {
response = client.post(requestUrl, body.getBytes(), header, contentType);
return response.bodyString();
} catch (QiniuException e) {
e.printStackTrace();
return null;
}
}
}
DTO
package com.example.honyee.qiniu.base;
public class QiniuAuditResult {
private Integer label;
private Float score;
private Boolean review;
public Integer getLabel() {
return label;
}
public void setLabel(Integer label) {
this.label = label;
}
public Float getScore() {
return score;
}
public void setScore(Float score) {
this.score = score;
}
public Boolean getReview() {
return review;
}
public void setReview(Boolean review) {
this.review = review;
}
}
package com.example.honyee.qiniu.base;
import java.util.Map;
public class QiniuAuditResultV2 {
private String suggestion;
private Map<String,Object> scenes;
public String getSuggestion() {
return suggestion;
}
public void setSuggestion(String suggestion) {
this.suggestion = suggestion;
}
public Map<String, Object> getScenes() {
return scenes;
}
public void setScenes(Map<String, Object> scenes) {
this.scenes = scenes;
}
}
package com.example.honyee.qiniu.base;
public class QiniuAuditCallback {
private Integer code;
private String name;
private String message;
private QiniuAuditResult result;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public QiniuAuditResult getResult() {
return result;
}
public void setResult(QiniuAuditResult result) {
this.result = result;
}
public Boolean isAuditPass(){
return 0 == code;
}
public Boolean belongSeqing(){
return this.result.getLabel() == 0;
}
}
package com.example.honyee.qiniu.base;
import java.util.Objects;
public class QiniuAuditCallbackV2 {
private Integer code;
private String message;
private QiniuAuditResultV2 result;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public QiniuAuditResultV2 getResult() {
return result;
}
public void setResult(QiniuAuditResultV2 result) {
this.result = result;
}
public boolean isAuditPass(){
return Objects.equals(200,code);
}
public Boolean isBlock(){
return "block".equals(this.result.getSuggestion());
}
public Boolean isReview(){
return "review".equals(this.result.getSuggestion());
}
}