package com.ctg.util;
import com.aliyun.oss.*;
import com.aliyun.oss.model.*;
import com.ctg.common.Const;
import com.ctg.pojo.dto.AliOssResult;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import javax.annotation.PostConstruct;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
/**
*
* @Description:阿里云上传文件工具类
* @version: v1.0.0
* @author: 刘 曾
* @date: 2018/8/11 17:24
*
* Modification History: Date Author Version Description
* ---------------------------------------------------------* 2018年8月11日
* Administrator v1.0.0 修改原因
*/
@Component
@Slf4j
public class AliOssUtil {
private static String BUCKET_NAME;
private static String KEY_ID;
private static String KEY_SECRET;
private static String END_POINT;
@Value("${oss.bucket}")
private String bucketName;
@Value("${oss.endPoint}")
private String accessEndPoint;
@Value("${oss.accessID}")
private String accessKeyId;
@Value("${oss.key}")
private String accessKeySecret;
@PostConstruct
public void init() {
BUCKET_NAME = bucketName;
KEY_ID = accessKeyId;
END_POINT = accessEndPoint;
KEY_SECRET = accessKeySecret;
}
private static OSSClient getOSSClient() {
OSSClient ossClient = new OSSClient(END_POINT, KEY_ID, KEY_SECRET);
return ossClient;
}
/**
* 上传文件
*
* @param file 文件流
* @param folderPath 要存放的文件夹路径,即阿里云的ObjectName(但不包括具体文件名称)
* @desc 状态 描述 文件名
* status msg fileName
* 0 上传文件成功 xxx.jpg
* 1 文件为空 ""
* 2 系统异常
*/
public static AliOssResult uploadFile(MultipartFile file, String folderPath) {
AliOssResult result = new AliOssResult();
//newName,随机生成的文件名
String newName = "";
OSSClient client = getOSSClient();
String bucketName = BUCKET_NAME;
InputStream inputStream = null;
try {
if (file != null && !file.isEmpty()) {
newName = UUID.randomUUID().toString() + file.getOriginalFilename().substring(
file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());
inputStream = file.getInputStream();
client.putObject(bucketName, folderPath + newName, inputStream);
} else {
result.setStatus(1);
result.setMsg("文件为空");
// result.setFileName("");
return result;
}
result.setStatus(0);
result.setMsg("存储文件成功");
List<String> imgList = new ArrayList<>();
imgList.add(newName);
result.setImgList(imgList);
return result;
} catch (Exception e) {
log.error("*********阿里云OSS上传文件出错了!*********\n"
+ e.getMessage());
e.printStackTrace();
result.setStatus(2);
result.setMsg(e.getMessage());
// result.setFileName("");
return result;
} finally {
// 关闭OSSClient。
try {
client.shutdown();
} catch (Exception e) {
log.error("*********关闭阿里云连接(OSSClient)出错了!*********", e.getMessage());
e.printStackTrace();
}
}
}
/**
* 删除文件
*
* @param imageLocation 图片在阿里云的完整路径,如:epc/mazda/part/aaa.jpg
* @throws OSSException
* @throws ClientException
* @throws FileNotFoundException
* @desc 状态 描述 文件名
* status msg fileName
* 0 删除文件成功 xxx.jpg
* 1 文件为空 ""
* 2 系统异常
*/
public static AliOssResult deleteFile(String imageLocation) {
AliOssResult result = new AliOssResult();
String newName = "";
OSSClient client = getOSSClient();
try {
String bucketName = BUCKET_NAME;
client.deleteObject(bucketName, imageLocation);
result.setStatus(0);
result.setMsg("删除文件成功");
List<String> imgList = new ArrayList<>();
imgList.add(newName);
result.setImgList(imgList);
// result.setFileName(newName);
return result;
} catch (Exception e) {
result.setStatus(2);
result.setMsg(e.getMessage());
return result;
} finally {
try {
client.shutdown();
} catch (Exception e) {
log.error("*********关闭阿里云连接(OSSClient)出错了!*********", e.getMessage());
e.printStackTrace();
}
}
}
/**
* 创建文件夹
*
* @param folder 文件夹名称,必须以"/"结尾,比如"aaa/",或者"aaa/bbb/"
* @throws Exception
*/
public static AliOssResult createFolder(String folder)
throws Exception {
AliOssResult result = new AliOssResult();
if (!StringUtils.endsWith(folder, "/")) {
result.setStatus(1);
result.setMsg("文件夹名称结尾必须带'/'");
return result;
}
OSSClient client = getOSSClient();
try {
String bucketName = BUCKET_NAME;
File file = new File(folder);
file.createNewFile();
client.putObject(bucketName, folder, file);
result.setStatus(0);
result.setMsg("创建文件夹成功");
return result;
} catch (Exception e) {
log.error("********** 创建文件夹失败。系统出错了!*********", e.getMessage());
e.printStackTrace();
result.setStatus(1);
result.setMsg("创建文件夹失败。系统出错了!");
return result;
} finally {
try {
client.shutdown();
} catch (Exception e) {
log.error("*********关闭阿里云连接(OSSClient)出错了!*********", e.getMessage());
e.printStackTrace();
}
}
}
/**
* 创建Bucket
*
* @param client
* @param bucketName
* @throws OSSException
* @throws ClientException
*/
public static void ensureBucket(OSSClient client, String bucketName) throws OSSException, ClientException {
try {
client.createBucket(bucketName);
} catch (ServiceException e) {
log.error("***********阿里云上传文件创建Bucket出错**********" + e.getMessage());
}
}
/**
* 删除一个Bucket和其中的Objects
*
* @param client
* @param bucketName
* @throws OSSException
* @throws ClientException
*/
private static void deleteBucket(OSSClient client, String bucketName) throws OSSException, ClientException {
try {
ObjectListing ObjectListing = client.listObjects(bucketName);
List<OSSObjectSummary> listDeletes = ObjectListing.getObjectSummaries();
for (int i = 0; i < listDeletes.size(); i++) {
String objectName = listDeletes.get(i).getKey();
log.info("************删除阿里云上Bucket和其中的Objects是***********", objectName);
//如果不为空,先删除bucket下的文件
client.deleteObject(bucketName, objectName);
}
client.deleteBucket(bucketName);
} catch (Exception e) {
log.error("***************删除阿里云上Bucket和其中的Objects失败*********************" + e.getMessage());
}
}
/**
* 把Bucket设置成所有人可读
*
* @param client
* @param bucketName
* @throws OSSException
* @throws ClientException
*/
private static void setBucketPublicReadable(OSSClient client, String bucketName) throws OSSException, ClientException {
//创建bucket
client.createBucket(bucketName);
//设置bucket的访问权限, public-read-write权限
client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
}
/**
* 上传文件
*
* @param client
* @param bucketName
* @param Objectkey
* @param filename
* @throws OSSException
* @throws ClientException
* @throws FileNotFoundException
*/
private static void uploadFile(OSSClient client, String bucketName, String Objectkey, String filename)
throws OSSException, ClientException, FileNotFoundException {
File file = new File(filename);
ObjectMetadata objectMeta = new ObjectMetadata();
objectMeta.setContentLength(file.length());
//判断上传类型,多的可根据自己需求来判定
if (filename.endsWith("xml")) {
objectMeta.setContentType("text/xml");
} else if (filename.endsWith("jpg")) {
objectMeta.setContentType("image/jpeg");
} else if (filename.endsWith("png")) {
objectMeta.setContentType("image/png");
}
InputStream input = new FileInputStream(file);
client.putObject(bucketName, Objectkey, input, objectMeta);
}
/**
* 下载文件
*
* @param client
* @param bucketName
* @param Objectkey
* @param filename
* @throws OSSException
* @throws ClientException
*/
private static void downloadFile(OSSClient client, String bucketName, String Objectkey, String filename)
throws OSSException, ClientException {
ObjectMetadata t = client.getObject(new GetObjectRequest(bucketName, Objectkey),
new File(filename));
client.shutdown();
}
/**
* 下载文件
*
* @param client
* @param bucketName
* @param Objectkey
* @param filename
* @throws OSSException
* @throws ClientException
*/
private static void downloadFile2(OSSClient client, String bucketName, String Objectkey, String filename)
throws OSSException, ClientException {
// 创建OSSClient实例。
OSSClient ossClient = getOSSClient();
// ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
OSSObject ossObject = ossClient.getObject(bucketName, filename);
// 读取文件内容。
System.out.println("Object content:");
try {
displayTextInputStream(ossObject.getObjectContent());
ossObject.close();
} catch (Exception e) {
} finally {
// 关闭OSSClient。
client.shutdown();
}
}
// public InputStream getObject(String resourceHost, String key) throws IOException {
// // 初始化OSSClient
// OSSClient client = new OSSClient(Const.Picture.endpoint, Const.Picture.accessKeyId, Const.Picture.accessKeySecret);
// InputStream objectContent = null;
// try {
// // 获取Object,返回结果为OSSObject对象
// OSSObject object = client.getObject(resourceHost, key);
// // 获取Object的输入流
// objectContent = object.getObjectContent();
// // 处理Object
// // 关闭流
// // objectContent.close();
// return objectContent;
// } catch (Exception e) {
// log.error("exception threw while getObject. resourceHost={}, key={}, exception={}",
// resourceHost, key, e);
// return objectContent;
// }
// }
/**
* 获取某个Object
*
* @param objectName
* @return
* @throws IOException
*/
public static InputStream getObject(String objectName) throws IOException {
// 初始化OSSClient
OSSClient client = getOSSClient();
InputStream objectContent = null;
try {
// 获取Object,返回结果为OSSObject对象
OSSObject object = client.getObject(BUCKET_NAME, objectName);
// 获取Object的输入流
objectContent = object.getObjectContent();
// System.out.println("Object content:");
// BufferedReader reader = new BufferedReader(new InputStreamReader(objectContent));
// while (true) {
// String line = reader.readLine();
// if (line == null) break;
// System.out.println("\n" + line);
// }
// 处理Object
// 关闭流
// objectContent.close();
return objectContent;
} catch (Exception e) {
log.error("exception threw while getObject. resourceHost={}, key={}, exception={}",
BUCKET_NAME, objectName, e);
return objectContent;
} finally {
try {
client.shutdown();
} catch (Exception e) {
log.error("*********关闭阿里云连接(OSSClient)出错了!*********", e.getMessage());
e.printStackTrace();
}
}
}
/**
* 分片上传MultipartUpload
*
* @param resourceHost
* @param key
* @param partFile
* @return
* @throws IOException
*/
public String uploadFile(String resourceHost, String key, MultipartFile partFile) throws IOException {
OSSClient client = new OSSClient(Const.Picture.endpoint, Const.Picture.accessKeyId, Const.Picture.accessKeySecret);
return multipartUpload(key, partFile, client, resourceHost);
}
private String multipartUpload(String key, MultipartFile partFile, OSSClient client, String bucketName) throws IOException {
// 开始Multipart Upload
InitiateMultipartUploadRequest initiateMultipartUploadRequest = new InitiateMultipartUploadRequest(bucketName, key);
InitiateMultipartUploadResult initiateMultipartUploadResult = client.initiateMultipartUpload(initiateMultipartUploadRequest);
final int partSize = 1024 * 1024 * 5;
// 计算分块数目
int partCount = (int) (partFile.getSize() / partSize);
if (partFile.getSize() % partSize != 0) {
partCount++;
}
// 新建一个List保存每个分块上传后的ETag和PartNumber
List<PartETag> partETags = new ArrayList<>();
for (int i = 0; i < partCount; i++) {
// 获取文件流
InputStream fis = partFile.getInputStream();
// 跳到每个分块的开头
long skipBytes = (long) partSize * i;
fis.skip(skipBytes);
// 计算每个分块的大小
long size = partSize < partFile.getSize() - skipBytes ?
partSize : partFile.getSize() - skipBytes;
// 创建UploadPartRequest,上传分块
UploadPartRequest uploadPartRequest = new UploadPartRequest();
uploadPartRequest.setBucketName(bucketName);
uploadPartRequest.setKey(key);
uploadPartRequest.setUploadId(initiateMultipartUploadResult.getUploadId());
uploadPartRequest.setInputStream(fis);
uploadPartRequest.setPartSize(size);
uploadPartRequest.setPartNumber(i + 1);
UploadPartResult uploadPartResult = client.uploadPart(uploadPartRequest);
// 将返回的PartETag保存到List中。
partETags.add(uploadPartResult.getPartETag());
// 关闭文件
fis.close();
}
CompleteMultipartUploadRequest completeMultipartUploadRequest =
new CompleteMultipartUploadRequest(bucketName, key, initiateMultipartUploadResult.getUploadId(), partETags);
// 完成分块上传
CompleteMultipartUploadResult completeMultipartUploadResult =
client.completeMultipartUpload(completeMultipartUploadRequest);
// 获得地址
return completeMultipartUploadResult.getKey();
}
/**
* @param request 上传阿里云Oss 只适合单张
* @param folderPath 上传的路径
* @return
* @throws Exception
*/
public static AliOssResult springUpload(HttpServletRequest request, String folderPath) throws Exception {
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
Iterator<String> iter = multiRequest.getFileNames();
OSSClient client = getOSSClient();
String bucketName = BUCKET_NAME;
InputStream inputStream = null;
AliOssResult result = new AliOssResult();
String newName = "";
List<String> imgList = new ArrayList<>();
try {
while (iter.hasNext()) {
MultipartFile file = multiRequest.getFile(iter.next().toString());
if (file != null && !file.isEmpty()) {
newName = UUID.randomUUID().toString().trim().replaceAll("-", "") + file.getOriginalFilename().substring(
file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());
inputStream = file.getInputStream();
// BufferedImage bufImg = ImageIO.read(inputStream);// 把图片读入到内存中
// // 压缩代码
// bufImg = Thumbnails.of(bufImg).width(1024).keepAspectRatio(true).outputQuality(0.8).asBufferedImage();
// ByteArrayOutputStream bos = new ByteArrayOutputStream();// 存储图片文件byte数组
// ImageIO.write(bufImg, "jpg", bos); // 图片写入到ImageOutputStream
// inputStream = new ByteArrayInputStream(bos.toByteArray());
client.putObject(bucketName, folderPath + newName, inputStream);
} else {
result.setStatus(1);
result.setMsg("文件为空");
return result;
}
imgList.add(newName);
}
} catch (Exception e) {
log.error("*********阿里云OSS上传文件出错了!*********\n"
+ e.getMessage());
e.printStackTrace();
result.setStatus(2);
result.setMsg(e.getMessage());
return result;
} finally {
// 关闭OSSClient。
try {
client.shutdown();
} catch (Exception e) {
log.error("*********关闭阿里云连接(OSSClient)出错了!*********", e.getMessage());
e.printStackTrace();
}
}
result.setImgList(imgList);
result.setStatus(0);
result.setMsg("上传图片成功");
return result;
}
private static void displayTextInputStream(InputStream input) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
while (true) {
String line = reader.readLine();
if (line == null) break;
System.out.println("\t" + line);
}
System.out.println();
reader.close();
}
public static AliOssResult downFileAndUpload(String fileName, String picturePath, String folderPath) {
AliOssResult result = new AliOssResult();
URL url = null;
String filepath = "";
//newName,随机生成的文件名
// String newName = "";
OSSClient client = getOSSClient();
String bucketName = BUCKET_NAME;
InputStream inputStream = null;
try {
url = new URL(picturePath);
inputStream = new DataInputStream(url.openStream());
// String path="DisPart/image/car/";
// AliOssResult aliOssResult = AliOssUtil.uploadFiles(dataInputStream, path);
if (inputStream != null) {
// newName = flieName;
client.putObject(bucketName, folderPath + fileName, inputStream);
} else {
result.setStatus(1);
result.setMsg("文件为空");
// result.setFileName("");
return result;
}
result.setStatus(0);
result.setMsg("存储文件成功");
// List imgList = new ArrayList<>();
// imgList.add(fileName);
// result.setImgList(imgList);
return result;
} catch (Exception e) {
log.error("*********阿里云OSS上传文件出错了!*********\n"
+ e.getMessage());
e.printStackTrace();
result.setStatus(2);
result.setMsg(e.getMessage());
// result.setFileName("");
return result;
} finally {
// 关闭OSSClient。
try {
client.shutdown();
} catch (Exception e) {
log.error("*********关闭阿里云连接(OSSClient)出错了!*********", e.getMessage());
e.printStackTrace();
}
}
}
/**
* @param request 上传阿里云Oss 多张
* @param folderPath 上传的路径 pzx
* @return
* @throws Exception
*/
public static AliOssResult springUploadOverride(HttpServletRequest request, String folderPath) throws Exception {
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
Iterator<String> iter = multiRequest.getFileNames();
OSSClient client = getOSSClient();
String bucketName = BUCKET_NAME;
InputStream inputStream = null;
AliOssResult result = new AliOssResult();
String newName = "";
List<String> imgList = new ArrayList<>();
try {
while (iter.hasNext()) {
MultipartFile file = multiRequest.getFile(iter.next().toString());
if (file != null && !file.isEmpty()) {
if (file.getOriginalFilename().lastIndexOf(".") != -1) {
// System.out.println("上传111111111111111111111》》》》》》》》》》》》》》》》》》》》"+file.getOriginalFilename());
newName = UUID.randomUUID().toString().trim().replaceAll("-", "") + file.getOriginalFilename().substring(
file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());
inputStream = file.getInputStream();
// BufferedImage bufImg = ImageIO.read(inputStream);// 把图片读入到内存中
// // 压缩代码
// bufImg = Thumbnails.of(bufImg).scale(0.8f).outputQuality(0.5f).asBufferedImage();
// ByteArrayOutputStream bos = new ByteArrayOutputStream();// 存储图片文件byte数组
// ImageIO.write(bufImg, "jpg", bos); // 图片写入到ImageOutputStream
// inputStream = new ByteArrayInputStream(bos.toByteArray());
client.putObject(bucketName, folderPath + newName, inputStream);
} else {
// System.out.println("上传2222222222222》》》》》》》》》》》》》》》》》》》》");
long start = System.currentTimeMillis();
newName = UUID.randomUUID().toString().trim().replaceAll("-", "") + ".png";
inputStream = file.getInputStream();
client.putObject(bucketName, folderPath + newName, inputStream);
long end1 = System.currentTimeMillis();
System.out.println("上传oss消耗时间》》》》》》》》》》》》》》》》》》》》" + (end1 - start));
}
} else {
result.setStatus(1);
result.setMsg("文件为空");
return result;
}
imgList.add(newName);
}
} catch (Exception e) {
log.error("*********阿里云OSS上传文件出错了!*********\n"
+ e.getMessage());
e.printStackTrace();
result.setStatus(2);
result.setMsg(e.getMessage());
return result;
} finally {
// 关闭OSSClient。
try {
client.shutdown();
} catch (Exception e) {
log.error("*********关闭阿里云连接(OSSClient)出错了!*********", e.getMessage());
e.printStackTrace();
}
}
result.setImgList(imgList);
result.setStatus(0);
result.setMsg("上传图片成功");
return result;
}
/**
* @param files 上传阿里云Oss 多张
* @param folderPath 上传的路径 pzx
* @return
* @throws Exception
*/
public static AliOssResult springUploadOverride1(List<MultipartFile> files, String folderPath) throws Exception {
Iterator<MultipartFile> iter = files.iterator();
OSSClient client = getOSSClient();
String bucketName = BUCKET_NAME;
InputStream inputStream = null;
AliOssResult result = new AliOssResult();
String newName = "";
List<String> imgList = new ArrayList<>();
try {
while (iter.hasNext()) {
MultipartFile file =iter.next();
if (file != null && !file.isEmpty()) {
if (file.getOriginalFilename().lastIndexOf(".") != -1) {
// System.out.println("上传111111111111111111111》》》》》》》》》》》》》》》》》》》》"+file.getOriginalFilename());
newName = UUID.randomUUID().toString().trim().replaceAll("-", "") + file.getOriginalFilename().substring(
file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());
inputStream = file.getInputStream();
// BufferedImage bufImg = ImageIO.read(inputStream);// 把图片读入到内存中
// // 压缩代码
// bufImg = Thumbnails.of(bufImg).scale(0.8f).outputQuality(0.5f).asBufferedImage();
// ByteArrayOutputStream bos = new ByteArrayOutputStream();// 存储图片文件byte数组
// ImageIO.write(bufImg, "jpg", bos); // 图片写入到ImageOutputStream
// inputStream = new ByteArrayInputStream(bos.toByteArray());
client.putObject(bucketName, folderPath + newName, inputStream);
} else {
// System.out.println("上传2222222222222》》》》》》》》》》》》》》》》》》》》");
long start = System.currentTimeMillis();
newName = UUID.randomUUID().toString().trim().replaceAll("-", "") + ".png";
inputStream = file.getInputStream();
client.putObject(bucketName, folderPath + newName, inputStream);
long end1 = System.currentTimeMillis();
System.out.println("上传oss消耗时间》》》》》》》》》》》》》》》》》》》》" + (end1 - start));
}
} else {
result.setStatus(1);
result.setMsg("文件为空");
return result;
}
imgList.add(newName);
}
} catch (Exception e) {
log.error("*********阿里云OSS上传文件出错了!*********\n"
+ e.getMessage());
e.printStackTrace();
result.setStatus(2);
result.setMsg(e.getMessage());
return result;
} finally {
// 关闭OSSClient。
try {
client.shutdown();
} catch (Exception e) {
log.error("*********关闭阿里云连接(OSSClient)出错了!*********", e.getMessage());
e.printStackTrace();
}
}
result.setImgList(imgList);
result.setStatus(0);
result.setMsg("上传图片成功");
return result;
}
}