第三方阿里云内容安全工具
1 依赖引入
在leadnews-common中引入阿里云sdk依赖
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-green</artifactId>
</dependency>
2 新建阿里云的配置文件 properties
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Q1pv4xCT-1611232606762)(D:/种子文件/黑马头条/黑马头条md备课讲义/day06/assets/1585885548911.png)]
在leadnews-common中的resources中新建aliyun.properties
aliyun.accessKeyId=LTAI4FmKL2EKYCGgN2az5M57 //-修改成自己阿里云服务的ak
aliyun.secret=XjgvRoAGzM3rWQxKWDJx98VWOmO0Hz //修改成自己阿里云服务的sk
aliyun.scenes=porn,terrorism,ad,qrcode,live,logo //内容检测场景
scenes,当前的这个场景设置,只有在图片审核的时候会用到,可以根据实际情况自由组合
3 引入工具类
3.1aliyun提供的三个类
ClientUploader.java CustomLibUploader.java UploadCredentials.java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.green.model.v20180509.UploadCredentialsRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.IClientProfile;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* 用于本地图片文件检测时,上传本地图片
*/
public class ClientUploader {
private IClientProfile profile;
private volatile UploadCredentials uploadCredentials;
private Map<String, String> headers;
private String prefix;
private boolean internal = false;
private Object lock = new Object();
private ClientUploader(IClientProfile profile, String prefix, boolean internal) {
this.profile = profile;
this.uploadCredentials = null;
this.headers = new HashMap<String, String>();
this.prefix = prefix;
this.internal = internal;
}
public static ClientUploader getImageClientUploader(IClientProfile profile, boolean internal){
return new ClientUploader(profile, "images", internal);
}
public static ClientUploader getVideoClientUploader(IClientProfile profile, boolean internal){
return new ClientUploader(profile, "videos", internal);
}
public static ClientUploader getVoiceClientUploader(IClientProfile profile, boolean internal){
return new ClientUploader(profile, "voices", internal);
}
public static ClientUploader getFileClientUploader(IClientProfile profile, boolean internal){
return new ClientUploader(profile, "files", internal);
}
/**
* 上传并获取上传后的图片链接
* @param filePath
* @return
*/
public String uploadFile(String filePath){
FileInputStream inputStream = null;
OSSClient ossClient = null;
try {
File file = new File(filePath);
UploadCredentials uploadCredentials = getCredentials();
if(uploadCredentials == null){
throw new RuntimeException("can not get upload credentials");
}
ObjectMetadata meta = new ObjectMetadata();
meta.setContentLength(file.length());
inputStream = new FileInputStream(file);
ossClient = new OSSClient(getOssEndpoint(uploadCredentials), uploadCredentials.getAccessKeyId(), uploadCredentials.getAccessKeySecret(), uploadCredentials.getSecurityToken());
String object = uploadCredentials.getUploadFolder() + '/' + this.prefix + '/' + String.valueOf(filePath.hashCode());
PutObjectResult ret = ossClient.putObject(uploadCredentials.getUploadBucket(), object, inputStream, meta);
return "oss://" + uploadCredentials.getUploadBucket() + "/" + object;
} catch (Exception e) {
throw new RuntimeException("upload file fail.", e);
} finally {
if(ossClient != null){
ossClient.shutdown();
}
if(inputStream != null){
try {
inputStream.close();
}catch (Exception e){
}
}
}
}
private String getOssEndpoint(UploadCredentials uploadCredentials){
if(this.internal){
return uploadCredentials.getOssInternalEndpoint();
}else{
return uploadCredentials.getOssEndpoint();
}
}
/**
* 上传并获取上传后的图片链接
* @param bytes
* @return
*/
public String uploadBytes(byte[] bytes){
OSSClient ossClient = null;
try {
UploadCredentials uploadCredentials = getCredentials();
if(uploadCredentials == null){
throw new RuntimeException("can not get upload credentials");
}
ossClient = new OSSClient(getOssEndpoint(uploadCredentials), uploadCredentials.getAccessKeyId(), uploadCredentials.getAccessKeySecret(), uploadCredentials.getSecurityToken());
String object = uploadCredentials.getUploadFolder() + '/' + this.prefix + '/' + UUID.randomUUID().toString();
PutObjectResult ret = ossClient.putObject(uploadCredentials.getUploadBucket(), object, new ByteArrayInputStream(bytes));
return "oss://" + uploadCredentials.getUploadBucket() + "/" + object;
} catch (Exception e) {
throw new RuntimeException("upload file fail.", e);
} finally {
if(ossClient != null){
ossClient.shutdown();
}
}
}
public void addHeader(String key, String value){
this.headers.put(key, value);
}
private UploadCredentials getCredentials() throws Exception{
if(this.uploadCredentials == null || this.uploadCredentials.getExpiredTime() < System.currentTimeMillis()){
synchronized(lock){
if(this.uploadCredentials == null || this.uploadCredentials.getExpiredTime() < System.currentTimeMillis()){
this.uploadCredentials = getCredentialsFromServer();
}
}
}
return this.uploadCredentials;
}
/**
* 从服务器端获取上传凭证
* @return
* @throws Exception
*/
private UploadCredentials getCredentialsFromServer() throws Exception{
UploadCredentialsRequest uploadCredentialsRequest = new UploadCredentialsRequest();
uploadCredentialsRequest.setAcceptFormat(FormatType.JSON); // 指定api返回格式
uploadCredentialsRequest.setMethod(com.aliyuncs.http.MethodType.POST); // 指定请求方法
uploadCredentialsRequest.setEncoding("utf-8");
uploadCredentialsRequest.setProtocol(ProtocolType.HTTP);
for (Map.Entry<String, String> kv : this.headers.entrySet()) {
uploadCredentialsRequest.putHeaderParameter(kv.getKey(), kv.getValue());
}
uploadCredentialsRequest.setHttpContent(new JSONObject().toJSONString().getBytes("UTF-8"), "UTF-8", FormatType.JSON);
IAcsClient client = null;
try{
client = new DefaultAcsClient(profile);
HttpResponse httpResponse = client.doAction(uploadCredentialsRequest);
if (httpResponse.isSuccess()) {
JSONObject scrResponse = JSON.parseObject(new String(httpResponse.getHttpContent(), "UTF-8"));
if (200 == scrResponse.getInteger("code")) {
JSONObject data = scrResponse.getJSONObject("data");
return new UploadCredentials(data.getString("accessKeyId"), data.getString("accessKeySecret"),
data.getString("securityToken"), data.getLongValue("expiredTime"),
data.getString("ossEndpoint"), data.getString("ossInternalEndpoint"), data.getString("uploadBucket"), data.getString("uploadFolder"));
}
String requestId = scrResponse.getString("requestId");
throw new RuntimeException("get upload credential from server fail. requestId:" + requestId + ", code:" + scrResponse.getInteger("code"));
}
throw new RuntimeException("get upload credential from server fail. http response status:" + httpResponse.getStatus());
}finally {
client.shutdown();
}
}
}
import javax.activation.MimetypesFileTypeMap;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
/**
* 用于自定义图库上传图片
*/
public class CustomLibUploader {
public String uploadFile(String host, String uploadFolder, String ossAccessKeyId,
String policy, String signature,
String filepath) throws Exception {
LinkedHashMap<String, String> textMap = new LinkedHashMap<String, String>();
// key
String objectName = uploadFolder + "/imglib_" + UUID.randomUUID().toString() + ".jpg";
textMap.put("key", objectName);
// Content-Disposition
textMap.put("Content-Disposition", "attachment;filename="+filepath);
// OSSAccessKeyId
textMap.put("OSSAccessKeyId", ossAccessKeyId);
// policy
textMap.put("policy", policy);
// Signature
textMap.put("Signature", signature);
Map<String, String> fileMap = new HashMap<String, String>();
fileMap.put("file", filepath);
String ret = formUpload(host, textMap, fileMap);
System.out.println("[" + host + "] post_object:" + objectName);
System.out.println("post reponse:" + ret);
return objectName;
}
private static String formUpload(String urlStr, Map<String, String> textMap, Map<String, String> fileMap) throws Exception {
String res = "";
HttpURLConnection conn = null;
String BOUNDARY = "9431149156168";
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(10000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new DataOutputStream(conn.getOutputStream());
// text
if (textMap != null) {
StringBuffer strBuf = new StringBuffer();
Iterator iter = textMap.entrySet().iterator();
int i = 0;
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
if (inputValue == null) {
continue;
}
if (i == 0) {
strBuf.append("--").append(BOUNDARY).append(
"\r\n");
strBuf.append("Content-Disposition: form-data; name=\""
+ inputName + "\"\r\n\r\n");
strBuf.append(inputValue);
} else {
strBuf.append("\r\n").append("--").append(BOUNDARY).append(
"\r\n");
strBuf.append("Content-Disposition: form-data; name=\""
+ inputName + "\"\r\n\r\n");
strBuf.append(inputValue);
}
i++;
}
out.write(strBuf.toString().getBytes());
}
// file
if (fileMap != null) {
Iterator iter = fileMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
if (inputValue == null) {
continue;
}
File file = new File(inputValue);
String filename = file.getName();
String contentType = new MimetypesFileTypeMap().getContentType(file);
if (contentType == null || contentType.equals("")) {
contentType = "application/octet-stream";
}
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(BOUNDARY).append(
"\r\n");
strBuf.append("Content-Disposition: form-data; name=\""
+ inputName + "\"; filename=\"" + filename
+ "\"\r\n");
strBuf.append("Content-Type: " + contentType + "\r\n\r\n");
out.write(strBuf.toString().getBytes());
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1)