You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

207 lines
6.4 KiB
Java

5 years ago
package com.bsd.cases.util;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.bsd.cases.conf.OssProperties;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.URL;
import java.util.Date;
@Component
public class OSSClientUtil {
private static final Logger logger = LoggerFactory.getLogger(OSSClientUtil.class);
//仓库名称
public String bucket;
//地域节点
public String endpoint;
//AccessKey ID 阿里云AccessKey
public String accessId ;
//Access Key Secret 阿里云Secret
public String accessKey;
private OSSClient ossClient;
private OssProperties ossProperties;
public OSSClientUtil(OssProperties ossProperties) {
this.ossProperties = ossProperties;
bucket = ossProperties.bucket;
endpoint = ossProperties.endpoint;
accessKey = ossProperties.accessKey;
accessId = ossProperties.accessId;
ossClient = new OSSClient(endpoint, accessId, accessKey);
}
/**
*
*/
// @PostConstruct
public void init() {
ossClient = new OSSClient(endpoint, accessId, accessKey);
}
/**
*
*/
public void destory() {
ossClient.shutdown();
}
/**
*
*
* @param url
* @throws Exception
*/
public void uploadImg2Oss(String url,String filedir) throws Exception {
File fileOnServer = new File(url);
FileInputStream fin;
try {
fin = new FileInputStream(fileOnServer);
String[] split = url.split("/");
this.uploadFile2OSS(fin, split[split.length - 1],filedir);
} catch (FileNotFoundException e) {
throw new Exception("图片上传失败");
}
}
public String uploadImg2Oss(MultipartFile file, String filedir) throws Exception {
if (file.getSize() > 10 * 1024 * 1024) {
throw new Exception("上传图片大小不能超过10M");
}
5 years ago
//文件名称
5 years ago
String originalFilename = file.getOriginalFilename();
5 years ago
//文件前缀
String timestamp = String.valueOf(new Date().getTime());
String fileName = originalFilename.substring(0,originalFilename.indexOf(".")) + timestamp;
//文件后缀
String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
5 years ago
// Random random = new Random();
5 years ago
String name = fileName +"."+ suffix;
5 years ago
try {
InputStream inputStream = file.getInputStream();
this.uploadFile2OSS(inputStream, name,filedir);
} catch (Exception e) {
5 years ago
e.printStackTrace();
5 years ago
}
5 years ago
return name;
5 years ago
}
/**
*
*
* @param fileUrl
* @return
*/
public String getImgUrl(String fileUrl,String filedir) {
System.out.println(fileUrl);
if (!StringUtils.isEmpty(fileUrl)) {
String[] split = fileUrl.split("/");
return this.getUrl(filedir + split[split.length - 1]);
}
return null;
}
/**
* OSS
*
* @param instream
* @param fileName
* @return "" ,MD5
*/
public String uploadFile2OSS(InputStream instream, String fileName,String filedir) {
String ret = "";
try {
// 创建上传Object的Metadata
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(instream.available());
objectMetadata.setCacheControl("no-cache");
objectMetadata.setHeader("Pragma", "no-cache");
objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
objectMetadata.setContentDisposition("inline;filename=" + fileName);
// 上传文件
PutObjectResult putResult = ossClient.putObject(bucket, filedir + fileName, instream, objectMetadata);
ret = putResult.getETag();
} catch (IOException e) {
logger.error(e.getMessage(), e);
} finally {
try {
if (instream != null) {
instream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
/**
* Description: OSScontentType
*
* @param filenameExtension
* @return String
*/
public static String getcontentType(String filenameExtension) {
if (filenameExtension.equalsIgnoreCase("bmp")) {
return "image/bmp";
}
if (filenameExtension.equalsIgnoreCase("gif")) {
return "image/gif";
}
if (filenameExtension.equalsIgnoreCase("jpeg") || filenameExtension.equalsIgnoreCase("jpg")
|| filenameExtension.equalsIgnoreCase("png")) {
return "image/jpeg";
}
if (filenameExtension.equalsIgnoreCase("html")) {
return "text/html";
}
if (filenameExtension.equalsIgnoreCase("txt")) {
return "text/plain";
}
if (filenameExtension.equalsIgnoreCase("vsd")) {
return "application/vnd.visio";
}
if (filenameExtension.equalsIgnoreCase("pptx") || filenameExtension.equalsIgnoreCase("ppt")) {
return "application/vnd.ms-powerpoint";
}
if (filenameExtension.equalsIgnoreCase("docx") || filenameExtension.equalsIgnoreCase("doc")) {
return "application/msword";
}
if (filenameExtension.equalsIgnoreCase("xml")) {
return "text/xml";
}
return "image/jpeg";
}
/**
* url
*
* @param key
* @return
*/
public String getUrl(String key) {
// 设置URL过期时间为10年 3600l* 1000*24*365*10
Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
// 生成URL
URL url = ossClient.generatePresignedUrl(bucket, key, expiration);
if (url != null) {
return url.toString();
}
return null;
}
}