xuekang
2024-05-11 bac0878349a1db23e7b420ea164e22fb9db73a99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
package com.nuvole.util;
 
import cn.hutool.core.io.FileUtil;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
 
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.time.Instant;
import java.util.Date;
import java.util.Properties;
 
/**
 * @author ChenLong
 * @version 1.0
 * @ClassName SFtpUtil
 * @date 2019/7/24 20:53
 */
public class OSSUtil {
 
    private static String bucketName = null;
    private static String endpoint = null;
    private static String endpointNet = null;
    private static String region = null;
    private static String accessKey = null;
    private static String secretKey = null;
 
    private static AmazonS3 amazonS3NetClient = null;
 
    public static Properties getYdOssProp() {
        Properties props = new Properties();
        InputStream in = null;
        try {
            ResourceLoader resourceLoader = new DefaultResourceLoader();
            in = resourceLoader.getResource("ydOss.properties").getInputStream();
            props.load(in);
            return props;
        } catch (IOException e) {
            e.printStackTrace();
            return props;
        } finally {
            ResourceUtil.safeClose(in);
        }
    }
//    private static AmazonS3 client = null;
 
    public static AmazonS3 ossInit() {
        Properties props = getYdOssProp();
        bucketName = props.getProperty("ydOss.bucketName");
        endpoint = props.getProperty("ydOss.endpoint");
        region = props.getProperty("ydOss.region");
        accessKey = props.getProperty("ydOss.accessKey");
        secretKey = props.getProperty("ydOss.secretKey");
        // 创建 AmazonS3 实例。
        AwsClientBuilder.EndpointConfiguration endpointConfiguration = new AwsClientBuilder.EndpointConfiguration(endpoint, region);
        BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
        AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
        AmazonS3 client = AmazonS3ClientBuilder.standard()
                .withEndpointConfiguration(endpointConfiguration)
                .withCredentials(credentialsProvider).build();
        return client;
    }
 
    /**
     * 获取外网oss地址
     *
     * @return
     */
    public static AmazonS3 ossNetInit() {
        if (amazonS3NetClient != null) {
            return amazonS3NetClient;
        }
        Properties props = getYdOssProp();
        bucketName = props.getProperty("ydOss.bucketName");
        endpointNet = props.getProperty("ydOss.endpointNet");
        region = props.getProperty("ydOss.region");
        accessKey = props.getProperty("ydOss.accessKey");
        secretKey = props.getProperty("ydOss.secretKey");
        // 创建 AmazonS3 实例。
        AwsClientBuilder.EndpointConfiguration endpointConfiguration = new AwsClientBuilder.EndpointConfiguration(endpointNet, region);
        BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
        AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
        amazonS3NetClient = AmazonS3ClientBuilder.standard()
                .withEndpointConfiguration(endpointConfiguration)
                .withCredentials(credentialsProvider).build();
        return amazonS3NetClient;
    }
 
    // 上传文件。
    public static void upload(AmazonS3 client, String fileName, InputStream inputStream, String targetPath) {
        if (targetPath.startsWith("/")) {
            targetPath = targetPath.substring(1);
        }
        String objectName = targetPath + "/" + fileName;
        objectName = objectName.replace("//", "/");
        mkdirFolder(client, targetPath);
 
        ObjectMetadata objectMetadata = new ObjectMetadata();
        try {
            // 设置对象(Object)大小。
            objectMetadata.setContentLength(inputStream.available());
            // 设置上传内容类型。
//            objectMetadata.setContentType("text/plain");
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        // 上传同时设置访问权限,例如'Private'私有权限。
        PutObjectRequest request = new PutObjectRequest(bucketName, objectName, inputStream, objectMetadata);
        request.setCannedAcl(CannedAccessControlList.Private);
        PutObjectResult putObjectResult = client.putObject(request);
//        PutObjectResult putObjectResult = client.putObject(bucketName, objectName, inputStream, null);
        if (putObjectResult == null) {
            return;
        }
        try {
//            return getShareUrl(objectName);
            return;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return;
    }
 
 
    public static void upload(AmazonS3 client, String sourceFilePath, String targetFilePath, boolean isDelSourceFile) {
        String targetPath = targetFilePath.substring(0, targetFilePath.lastIndexOf("/"));
        System.out.println("上传 本地路径" + sourceFilePath+" 上传到 " + targetFilePath);
        File file = new File(sourceFilePath);
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return;
        }
        upload(client, file.getName(), fileInputStream, targetPath);
 
        if (isDelSourceFile) {
            FileUtil.del(sourceFilePath);
        }
        return;
    }
 
    public static void upload(AmazonS3 client, String FileName, BufferedImage bufferedImage, String targetPath)
            throws IOException {
        if (FileName.lastIndexOf(".") <= -1) {
            return;
        }
        String ext = FileName.substring(FileName.lastIndexOf(".") + 1);
        String sourceFilePath = System.getProperty("user.dir") + ResourceUtil.createFileName(ext);
        File tmpFile = FileUtil.touch(sourceFilePath);
        ImageIO.write(bufferedImage, "png", tmpFile);
        System.out.println("targetPath" + targetPath);
        upload(client, sourceFilePath, targetPath + FileName, true);
    }
 
    public static void download(AmazonS3 client, String sourceFilePath, String targetFilePath) {
        if (StringUtils.isEmpty(sourceFilePath)){
            return;
        }
        if (sourceFilePath.startsWith("/")){
            sourceFilePath = sourceFilePath.substring(1);
        }
        // 将文件(Object)下载到文件中,并返回文件(Object)的元数据。
        GetObjectRequest request = new GetObjectRequest(bucketName, sourceFilePath);
        ObjectMetadata meta = client.getObject(request, FileUtil.touch(targetFilePath));
    }
 
    /**
     * 创建文件夹
     *
     * @return
     */
    private static boolean mkdirFolder(AmazonS3 client, String directory) {
        String folder = String.copyValueOf(directory.toCharArray());
        if (directory.startsWith("/")) {
            folder = folder.substring(1);
        }
        if (!folder.endsWith("/")) {
            folder = folder + "/";
        }
        PutObjectResult putObjectResult = client.putObject(bucketName, folder, new ByteArrayInputStream(new byte[0]), null);
        return putObjectResult != null;
    }
 
    /**
     * 获取对象的分享链接
     *
     * @param objectName
     * @return
     */
    public static String getShareUrl(String objectName) {
        ossNetInit();
        // 生成可预览的外链。
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName);
 
        // 设置过期时间,当到达该时间点时,URL 就会过期,其他人不再能访问该对象(Object)。
        Date expiration = new Date();
        // 设置 30 分钟后过期。
        long expTimeMillis = Instant.now().toEpochMilli();
        expTimeMillis += 1000 * 60 * 10;
        expiration.setTime(expTimeMillis);
 
        request.setExpiration(expiration);
 
        // 设置返回头
        // 设置为 "inline" 时在浏览器中展示,设置为 "attachment" 时以文件形式下载。
        // 此外设置为 "attachment;filename=\"filename.jpg\"" ,还可以让下载的文件名字重命名为 "filename.jpg"。
        ResponseHeaderOverrides headerOverrides = new ResponseHeaderOverrides();
        headerOverrides.setContentDisposition("inline");
        request.setResponseHeaders(headerOverrides);
 
        URL url = amazonS3NetClient.generatePresignedUrl(request);
        return url.toString();
    }
 
    public static void close(AmazonS3 client) {
        if (client != null) {
            client.shutdown();
        }
    }
 
    public static void main(String[] args) {
        // 创建 AmazonS3 实例。
        endpoint = "https://eos-beijing-7.cmecloud.cn";
        region = "beijing7";
        accessKey = "EDVFWAO1INQKHGJ78MK0";
        secretKey = "rQSMQ02h6oQPMaZyXR85XxLVhZh92jrwXFRkX6FX";
        bucketName = "ecosphere";
        AwsClientBuilder.EndpointConfiguration endpointConfiguration = new AwsClientBuilder.EndpointConfiguration(endpoint, region);
        BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
        AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
        AmazonS3 amazonS3 = AmazonS3ClientBuilder.standard()
                .withEndpointConfiguration(endpointConfiguration)
                .withCredentials(credentialsProvider).build();
        OSSUtil.download(amazonS3, "/ecosphereBase/2024/1/3/5894af65566a44a791baa4246bd5910a.csv", "C:\\Users\\cy\\Desktop\\新建文件夹\\b.csv");
        OSSUtil.close(amazonS3);
    }
 
 
}