123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274 |
- package com.fdkankan.fyun.s3;
- import cn.hutool.core.collection.CollUtil;
- import com.amazonaws.services.s3.AmazonS3;
- import com.amazonaws.services.s3.model.*;
- import com.fdkankan.fyun.constant.FYunConstants;
- import com.fdkankan.fyun.face.AbstractFYunFileService;
- import org.apache.commons.lang3.StringUtils;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
- import org.springframework.stereotype.Component;
- import org.springframework.util.ObjectUtils;
- import java.io.*;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
- import java.util.stream.Collectors;
- @Component
- @ConditionalOnProperty(name = "fyun.type",havingValue = "aws")
- public class S3FileService extends AbstractFYunFileService {
- private Logger log = LoggerFactory.getLogger(this.getClass().getName());
- @Autowired
- private AmazonS3 s3;
- @Override
- public String uploadFile(String bucket, byte[] data, String remoteFilePath){
- try {
- ObjectMetadata metadata = new ObjectMetadata();
- PutObjectRequest request = new PutObjectRequest(bucket, remoteFilePath, new ByteArrayInputStream(data), metadata);
- request.withCannedAcl(CannedAccessControlList.PublicRead);
- s3.putObject(request);
- } catch (Exception e) {
- log.error("s3上传文件失败", e);
- }
- return null;
- }
- @Override
- public String uploadFile(String bucket, String filePath, String remoteFilePath){
- return uploadFile(bucket, filePath, remoteFilePath,true,null);
- }
- @Override
- public String uploadFile(String bucket, String filePath, String remoteFilePath, Map<String, String> headers){
- return uploadFile(bucket, filePath, remoteFilePath,true,headers);
- }
- private String uploadFile(String bucket, String filePath, String remoteFilePath, Boolean shutdown,Map<String, String> headers){
- try {
- File file = new File(filePath);
- if (!file.exists()) {
- log.info("要上传s3的文件不存在");
- return null;
- }
- // 设置文件并设置公读
- ObjectMetadata metadata = new ObjectMetadata();
- if (filePath.contains(".jpg")) {
- metadata.setContentType("image/jpeg");
- }
- if (filePath.contains(".png")) {
- metadata.setContentType("image/png");
- }
- if(org.apache.commons.lang3.ObjectUtils.isNotEmpty(headers)){
- for (Map.Entry<String, String> header : headers.entrySet()) {
- metadata.setHeader(header.getKey(),header.getValue());
- }
- }
- PutObjectRequest request = new PutObjectRequest(bucket, remoteFilePath, file);
- request.withCannedAcl(CannedAccessControlList.PublicRead);
- request.withMetadata(metadata);
- // 上传文件
- PutObjectResult putObjectResult = s3.putObject(request);
- if (StringUtils.isNotEmpty(putObjectResult.getETag())) {
- log.info("s3上传文件成功:" + remoteFilePath);
- }
- } catch (Exception e) {
- log.error("文件上传失败:{}",filePath);
- e.printStackTrace();
- }
- return null;
- }
- @Override
- public String uploadFileByCommand(String bucket, String filePath, String remoteFilePath){
- String ossPath = bucket + "/" + remoteFilePath;
- try {
- String command = String.format(FYunConstants.UPLOAD_SH, ossPath, filePath);
- log.info("开始上传文件, ossPath:{}, srcPath:{}", ossPath, filePath);
- callshell(command);
- } catch (Exception e) {
- log.error("上传文件失败, ossPath:{}, srcPath:{}", ossPath, filePath);
- e.printStackTrace();
- }
- return null;
- }
- @Override
- public void deleteFile(String bucket, String remoteFilePath){
- if (remoteFilePath.startsWith("/")) {
- remoteFilePath = remoteFilePath.substring(1);
- }
- try {
- s3.deleteObject(bucket, remoteFilePath);
- } catch (Exception e) {
- log.error("s3删除文件失败,key=" + remoteFilePath, e);
- }
- }
- @Override
- public void deleteFolder(String bucket, String remoteFolderPath){
- try {
- int maxKeys = 200;
- String nextMaker = null;
- ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
- listObjectsRequest.setBucketName(bucket);
- listObjectsRequest.setPrefix(remoteFolderPath);
- listObjectsRequest.setMaxKeys(maxKeys);
- com.amazonaws.services.s3.model.ObjectListing objectListing;
- do {
- listObjectsRequest.setMarker(nextMaker);
- objectListing = s3.listObjects(listObjectsRequest);
- List<S3ObjectSummary> objectSummaries = objectListing.getObjectSummaries();
- List<DeleteObjectsRequest.KeyVersion> keys = objectSummaries.stream().map(summary -> new DeleteObjectsRequest.KeyVersion(summary.getKey())).collect(Collectors.toList());
- DeleteObjectsRequest multiObjectDeleteRequest = new DeleteObjectsRequest(bucket)
- .withKeys(keys).withQuiet(false);
- DeleteObjectsResult delObjRes = s3.deleteObjects(multiObjectDeleteRequest);
- int successfulDeletes = delObjRes.getDeletedObjects().size();
- log.info("删除aws文件成功,删除文件数;{}", successfulDeletes);
- nextMaker = objectListing.getNextMarker();
- } while (objectListing.isTruncated());
- } catch (Exception e) {
- log.error("删除was文件失败,path=" + remoteFolderPath, e);
- }
- }
- @Override
- public void uploadMulFiles(String bucket, Map<String, String> filepaths){
- try {
- for (Map.Entry<String, String> entry : filepaths.entrySet()) {
- uploadFile(bucket, entry.getKey(), entry.getValue(), false,null);
- }
- } catch (Exception e) {
- log.error("OSS批量上传文件失败!");
- }
- }
- @Override
- public List<String> listRemoteFiles(String bucket, String sourcePath){
- return listRemoteFiles(bucket, sourcePath, true);
- }
- private List<String> listRemoteFiles(String bucket, String sourcePath, Boolean shutdown) {
- List<String> keyList = new ArrayList<>();
- try {
- boolean flag = true;
- String nextMaker = null;
- ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
- listObjectsRequest.setBucketName(bucket);
- listObjectsRequest.setPrefix(sourcePath);
- listObjectsRequest.setMaxKeys(200);
- do {
- listObjectsRequest.setMarker(nextMaker);
- ObjectListing objectListing = s3.listObjects(listObjectsRequest);
- List<S3ObjectSummary> objectSummaries = objectListing.getObjectSummaries();
- List<String> collect = objectSummaries.stream().map(S3ObjectSummary::getKey).collect(Collectors.toList());
- if (CollUtil.isNotEmpty(collect)) {
- keyList.addAll(collect);
- }
- nextMaker = objectListing.getNextMarker();
- flag = objectListing.isTruncated();
- } while (flag);
- } catch (Exception e) {
- log.error("获取文件列表失败,path=" + sourcePath, e);
- e.printStackTrace();
- }
- return keyList;
- }
- @Override
- public void copyFileBetweenBucket(String sourceBucketName, String sourcePath, String targetBucketName, String targetPath){
- copyFileBetweenBucket(sourceBucketName, sourcePath, targetBucketName, targetPath, true);
- }
- private void copyFileBetweenBucket(String sourceBucketName, String sourcePath, String targetBucketName, String targetPath, Boolean shutdown){
- try {
- List<String> files = listRemoteFiles(sourceBucketName, sourcePath, false);
- if (ObjectUtils.isEmpty(files)) {
- log.error("源文件夹为空:{}", sourcePath);
- }
- files.stream().forEach(file -> {
- CopyObjectRequest request = new CopyObjectRequest(sourceBucketName, file, targetBucketName, file.replace(sourcePath, targetPath));
- request.withCannedAccessControlList(CannedAccessControlList.PublicRead);
- s3.copyObject(request);
- });
- } catch (Exception e) {
- log.error("列举文件目录失败,key=" + sourcePath);
- }
- }
- @Override
- public void copyFilesBetweenBucket(String sourceBucketName, String targetBucketName, Map<String, String> pathMap){
- if (ObjectUtils.isEmpty(pathMap)) {
- return;
- }
- try {
- for (Map.Entry<String, String> entry : pathMap.entrySet()) {
- copyFileBetweenBucket(sourceBucketName, entry.getKey(), targetBucketName, entry.getValue(), false);
- }
- } catch (Exception e) {
- log.error("批量复制文件失败!");
- }
- }
- @Override
- public String getFileContent(String bucketName, String remoteFilePath){
- try {
- GetObjectRequest request = new GetObjectRequest(bucketName,remoteFilePath);
- S3Object object = s3.getObject(request);
- S3ObjectInputStream inputStream = object.getObjectContent();
- StringBuilder content = new StringBuilder();
- try(BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))){
- while (true) {
- String line = reader.readLine();
- if (line == null) break;
- content.append(line);
- }
- } catch (IOException e) {
- log.error("读取aws文件流失败", e);
- }
- object.close();
- return content.toString();
- } catch (Exception e) {
- log.error("获取文件内容失败:{}", remoteFilePath);
- return null;
- }
- }
- @Override
- public boolean fileExist(String bucket, String objectName) {
- try {
- return s3.doesObjectExist(bucket, objectName);
- } catch (Exception e) {
- log.error("判断文件是否存在失败:{}", objectName);
- return false;
- }
- }
- @Override
- public void downloadFile(String bucket, String remoteFilePath, String localPath) {
- try {
- File localFile = new File(localPath);
- if (!localFile.getParentFile().exists()) {
- localFile.getParentFile().mkdirs();
- }
- GetObjectRequest request = new GetObjectRequest(bucket, remoteFilePath);
- s3.getObject(request,new File(localPath));
- } catch (Throwable throwable) {
- log.error("文件下载失败:{}", remoteFilePath);
- throwable.printStackTrace();
- }
- }
- }
|