package cn.jxjypt.el.utils.oss;
import cn.jxjypt.el.utils.oConvertUtils;
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.FileItemStream;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Date;
import java.util.UUID;
@Slf4j
public class OssBootUtil {
private static String endPoint;
private static String accessKeyId;
private static String accessKeySecret;
private static String bucketName;
private static String staticDomain;
private static String rootDir;
public static void setEndPoint(String endPoint) {
OssBootUtil.endPoint = endPoint;
}
public static void setAccessKeyId(String accessKeyId) {
OssBootUtil.accessKeyId = accessKeyId;
}
public static void setAccessKeySecret(String accessKeySecret) {
OssBootUtil.accessKeySecret = accessKeySecret;
}
public static void setBucketName(String bucketName) {
OssBootUtil.bucketName = bucketName;
}
public static void setStaticDomain(String staticDomain) {
OssBootUtil.staticDomain = staticDomain;
}
public static void setRootDir(String rootDir) { OssBootUtil.rootDir = rootDir; }
public static String getStaticDomain() {
return staticDomain;
}
public static String getEndPoint() {
return endPoint;
}
public static String getAccessKeyId() {
return accessKeyId;
}
public static String getAccessKeySecret() {
return accessKeySecret;
}
public static String getBucketName() {
return bucketName;
}
public static OSSClient getOssClient() {
return ossClient;
}
public static String getRootDir() { return rootDir; }
private static OSSClient ossClient = null;
public static String upload(MultipartFile file, String fileDir,String customBucket) {
String FILE_URL = null;
initOSS(endPoint, accessKeyId, accessKeySecret);
StringBuilder fileUrl = new StringBuilder();
String newBucket = bucketName;
if(oConvertUtils.isNotEmpty(customBucket)){
newBucket = customBucket;
}
try {
if(!ossClient.doesBucketExist(newBucket)){
ossClient.createBucket(newBucket);
}
String orgName = file.getOriginalFilename();
if("" == orgName){
orgName=file.getName();
}
orgName = getFileName(orgName);
String fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
if (!fileDir.endsWith("/") && !fileDir.isEmpty()) {
fileDir = fileDir.concat("/");
}
if (!rootDir.endsWith("/") && !rootDir.isEmpty()){
fileDir = rootDir.concat("/").concat(fileDir);
}else{
fileDir = rootDir.concat(fileDir);
}
fileUrl = fileUrl.append(fileDir + fileName);
if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
FILE_URL = staticDomain + "/" + fileUrl;
} else {
FILE_URL = "https://" + newBucket + "." + endPoint + "/" + fileUrl;
}
PutObjectResult result = ossClient.putObject(newBucket, fileUrl.toString(), file.getInputStream());
if (result != null) {
log.info("------OSS文件上传成功------" + fileUrl);
}
} catch (IOException e) {
log.error(e.getMessage(),e);
return null;
}
return FILE_URL;
}
public static String upload(MultipartFile file, String fileDir) {
return upload(file, fileDir,null);
}
public static String upload(FileItemStream file, String fileDir) {
String FILE_URL = null;
initOSS(endPoint, accessKeyId, accessKeySecret);
StringBuilder fileUrl = new StringBuilder();
try {
String suffix = file.getName().substring(file.getName().lastIndexOf('.'));
String fileName = UUID.randomUUID().toString().replace("-", "") + suffix;
if (!fileDir.endsWith("/")) {
fileDir = fileDir.concat("/");
}
fileUrl = fileUrl.append(fileDir + fileName);
if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
FILE_URL = staticDomain + "/" + fileUrl;
} else {
FILE_URL = "https://" + bucketName + "." + endPoint + "/" + fileUrl;
}
PutObjectResult result = ossClient.putObject(bucketName, fileUrl.toString(), file.openStream());
ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
if (result != null) {
log.info("------OSS文件上传成功------" + fileUrl);
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
return FILE_URL;
}
public static void deleteUrl(String url) {
deleteUrl(url,null);
}
public static void deleteUrl(String url,String bucket) {
String newBucket = bucketName;
if(oConvertUtils.isNotEmpty(bucket)){
newBucket = bucket;
}
String bucketUrl = "";
if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
bucketUrl = staticDomain + "/" ;
} else {
bucketUrl = "https://" + newBucket + "." + endPoint + "/";
}
url = url.replace(bucketUrl,"");
ossClient.deleteObject(newBucket, url);
}
public static void delete(String fileName) {
ossClient.deleteObject(bucketName, fileName);
}
public static InputStream getOssFile(String objectName,String bucket){
InputStream inputStream = null;
try{
String newBucket = bucketName;
if(oConvertUtils.isNotEmpty(bucket)){
newBucket = bucket;
}
initOSS(endPoint, accessKeyId, accessKeySecret);
OSSObject ossObject = ossClient.getObject(newBucket,objectName);
inputStream = new BufferedInputStream(ossObject.getObjectContent());
}catch (Exception e){
log.info("文件获取失败" + e.getMessage());
}
return inputStream;
}
public static InputStream getOssFile(String objectName){
return getOssFile(objectName,null);
}
public static String download2localfile(String ossFileUrl){
String ossFileName = ossFileUrl.replace(staticDomain,"");
if(ossFileName.startsWith("/"))
ossFileName = ossFileName.substring(1,ossFileName.length());
String[] strings = ossFileName.split("/");
InputStream is = OssBootUtil.getOssFile(ossFileName);
if (is==null)
return null;
String tmpdir = System.getProperty("java.io.tmpdir");
if (!tmpdir.endsWith("/"))
tmpdir=tmpdir+"/";
String filename=tmpdir +strings[strings.length-1];
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filename);
byte[] b = new byte[1024];
int length;
while ((length = is.read(b)) > 0){
fos.write(b, 0, length);
}
is.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
return filename;
}
public static String getObjectURL(String bucketName, String objectName, Date expires) {
initOSS(endPoint, accessKeyId, accessKeySecret);
try{
if(ossClient.doesObjectExist(bucketName,objectName)){
URL url = ossClient.generatePresignedUrl(bucketName,objectName,expires);
return URLDecoder.decode(url.toString(),"UTF-8");
}
}catch (Exception e){
log.info("文件路径获取失败" + e.getMessage());
}
return null;
}
private static OSSClient initOSS(String endpoint, String accessKeyId, String accessKeySecret) {
if (ossClient == null) {
ossClient = new OSSClient(endpoint,
new DefaultCredentialProvider(accessKeyId, accessKeySecret),
new ClientConfiguration());
}
return ossClient;
}
public static String upload(InputStream stream, String relativePath) {
String FILE_URL = null;
String fileUrl = relativePath;
initOSS(endPoint, accessKeyId, accessKeySecret);
if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) {
FILE_URL = staticDomain + "/" + relativePath;
} else {
FILE_URL = "https://" + bucketName + "." + endPoint + "/" + fileUrl;
}
PutObjectResult result = ossClient.putObject(bucketName, fileUrl.toString(),stream);
ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
if (result != null) {
log.info("------OSS文件上传成功------" + fileUrl);
}
return FILE_URL;
}
public static String getFileName(String fileName){
int unixSep = fileName.lastIndexOf('/');
int winSep = fileName.lastIndexOf('\\');
int pos = (winSep > unixSep ? winSep : unixSep);
if (pos != -1) {
fileName = fileName.substring(pos + 1);
}
fileName = fileName.replace("=","").replace(",","").replace("&","").replace("#", "");
return fileName;
}
}
**调用实例:**
@ApiOperation("图片上传")
@Log("图片上传")
@PostMapping(value = "/uploadImg")
public ResponseEntity<Object> uploadImg(
@RequestParam(name = "file",required = true) MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
Map resultMap=new HashMap();
String fileName = file.getOriginalFilename().toLowerCase(Locale.ROOT);
long fileSize = file.getSize() / 1024;
String fileType=fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
if(fileType.equals("jpg")||fileType.equals("jpeg")||fileType.equals("png")){
}else{
throw new BadRequestException("图片格式不对,请按要求上传!");
}
log.info("======fileName: " + fileName + " fileSize:" + fileSize);
if(file.getSize()>(1024*1024*1)){
throw new BadRequestException("图片太大,请控制在1M以内!");
}
String url= OssBootUtil.upload(file,"JPK/***/");
log.info(url);
if(org.apache.commons.lang.StringUtils.isEmpty(url)){
throw new BadRequestException("上传失败");
}
resultMap.put("imgUrl",url);
return ResponseEntity.ok(resultMap);
}