中扬CRM客户关系管理系统
#
Junjie
2023-09-08 f57e1cf99a1516983d75a2522fd9f0ff3c56b65a
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
package com.zy.crm.common.service;
 
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.core.common.SnowflakeIdWorker;
import com.core.exception.CoolException;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
 
import java.io.*;
import java.net.URL;
import java.nio.file.Path;
import java.util.Date;
import java.nio.file.StandardCopyOption;
import java.nio.file.Files;
import java.nio.file.Paths;
 
/**
 * 阿里云OSS服务类
 * Created by vincent on 2019-11-26
 */
@Data
@Service("ossService")
public class OssService {
 
    private static Logger log = LoggerFactory.getLogger(OssService.class);
 
    private static final String OSS_ENDPOINT = "http://oss-cn-hangzhou.aliyuncs.com";
 
    @Value("${aliyun.oss.id}")
    private String accessKeyId;
 
    @Value("${aliyun.oss.secret}")
    private String accessKeySecret;
 
    @Value("${aliyun.oss.bucket}")
    private String bucket;
 
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
 
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
 
    /**
     * 上传OSS文件
     * @return the url
     */
    @Deprecated
    public String upload(InputStream inputStream, String suffix){
        if(suffix.trim().equals("file")){
            suffix="jpg";
        }
        OSSClient ossClient = new OSSClient(OSS_ENDPOINT, accessKeyId, accessKeySecret);
        String name = "";
        try {
            if (!ossClient.doesBucketExist(bucket)) {
                ossClient.createBucket(bucket);
                log.info("您的Bucket不存在,创建Bucket:{}",bucket);
            }
            name = String.valueOf(snowflakeIdWorker.nextId()).concat(".").concat(suffix);
            // 添加 ContentType
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType("image/jpg");
            ossClient.putObject(bucket, name, inputStream, objectMetadata);
            Date expiration = new Date(new Date().getTime() + 3600L * 1000 * 24 * 365 * 100);
            URL url = ossClient.generatePresignedUrl(bucket, name, expiration);
            log.info("OSS文件上传成功: {}", name);
//            return String.valueOf(url);
            return "http://tjdt.oss-cn-hangzhou.aliyuncs.com/"+name;
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
        throw new CoolException("500-上传失败");
    }
 
    @Deprecated
    public String upload(InputStream inputStream, String suffix,String contentType){
        if(suffix.trim().equals("file")){
            suffix="jpg";
        }
        OSSClient ossClient = new OSSClient(OSS_ENDPOINT, accessKeyId, accessKeySecret);
        String name = "";
        try {
            if (!ossClient.doesBucketExist(bucket)) {
                ossClient.createBucket(bucket);
                log.info("您的Bucket不存在,创建Bucket:{}",bucket);
            }
            name = String.valueOf(snowflakeIdWorker.nextId()).concat(".").concat(suffix);
            // 添加 ContentType
            ObjectMetadata objectMetadata = new ObjectMetadata();
//            objectMetadata.setContentType("image/jpg");
            objectMetadata.setContentType(contentType);
            ossClient.putObject(bucket, name, inputStream, objectMetadata);
            Date expiration = new Date(new Date().getTime() + 3600L * 1000 * 24 * 365 * 100);
            URL url = ossClient.generatePresignedUrl(bucket, name, expiration);
            log.info("OSS文件上传成功: {}", name);
//            return String.valueOf(url);
            return "http://zhongyang-ftpserver.oss-cn-hangzhou.aliyuncs.com/"+name;
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
        throw new CoolException("500-上传失败");
    }
 
    @Deprecated
    public String upload(InputStream inputStream) {
        return upload(inputStream, ".jpg");
    }
 
    /**
     * 文件上传
     * @param filePath OSS路径
     * @param file 文件File
     */
    public boolean uploadFile(String filePath, File file) {
        OSSClient ossClient = new OSSClient(OSS_ENDPOINT, accessKeyId, accessKeySecret);
        // 创建PutObjectRequest对象。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, filePath, file);
        // 上传文件。
        PutObjectResult result = ossClient.putObject(putObjectRequest);
        return true;
    }
 
    /**
     * 下载文件
     * @param filePath OSS路径
     */
    public ResponseEntity<InputStreamResource> downloadFile(String filePath) throws IOException {
        OSSClient ossClient = new OSSClient(OSS_ENDPOINT, accessKeyId, accessKeySecret);
        OSSObject ossObject = ossClient.getObject(bucket, filePath);
        InputStream inputStream = ossObject.getObjectContent();
 
        // 创建响应实体,将输出流作为文件内容返回
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "output.docx");
        InputStreamResource resource = new InputStreamResource(convertToByteArrayInputStream(inputStream));
        return ResponseEntity.ok()
                .headers(headers)
                .body(resource);
    }
 
    public static ByteArrayInputStream convertToByteArrayInputStream(InputStream inputStream) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        byte[] data = outputStream.toByteArray();
        return new ByteArrayInputStream(data);
    }
 
    /**
     * 下载OSS文件
     */
//    public void download(String name) {
//        OSSClient ossClient = new OSSClient(OSS_ENDPOINT, accessKeyId, accessKeySecret);
//        try {
//            OSSObject ossObject = ossClient.getObject(bucket, name);
//            InputStream inputStream = ossObject.getObjectContent();
//            // do transfer
//            inputStream.close();
//            log.info("OSS文件下载成功: {}", name);
//        } catch (Exception e){
//            e.printStackTrace();
//        } finally {
//            ossClient.shutdown();
//        }
//    }
 
    @Deprecated
    public String download(String name) {
        OSSClient ossClient = new OSSClient(OSS_ENDPOINT, accessKeyId, accessKeySecret);
        try {
            OSSObject ossObject = ossClient.getObject(bucket, name);
            InputStream inputStream = ossObject.getObjectContent();
 
            // 获取默认下载目录
            String defaultDownloadDir = System.getProperty("user.home") + "/Downloads";
 
            // 创建文件保存路径
            Path filePath = Paths.get(defaultDownloadDir, name);
 
            // 将输入流复制到文件
            Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
 
            // 关闭输入流
            inputStream.close();
 
            log.info("OSS文件下载成功,保存路径: {}", filePath);
            return ""+filePath;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
        return "";
    }
 
    /**
     * 删除OSS文件
     */
    public boolean delete(String name) {
        OSSClient ossClient = new OSSClient(OSS_ENDPOINT, accessKeyId, accessKeySecret);
        try {
            ossClient.deleteObject(bucket, name);
        } catch (Exception e){
            e.printStackTrace();
            return false;
        } finally {
            ossClient.shutdown();
        }
        return true;
    }
 
    public static void main(String[] args) {
        File file = new File("E:\\tmp\\v2-fbbb97b977b5cebc66dc3cefab0ac981_r.jpg");
        try {
            InputStream in = new FileInputStream(file);
            OssService ossService = new OssService();
            ossService.setAccessKeyId("LTAI4GDzr6ioSHuRw2mk22ug");
            ossService.setAccessKeySecret("84CHL7tF21LbU1qpaP0jn9mIAZP9bv");
            ossService.setBucket("tjdt");
            ossService.setEndpoint("http://oss-cn-hangzhou.aliyuncs.com");
            ossService.setSnowflakeIdWorker(new SnowflakeIdWorker());
            System.out.println(ossService.upload(in));
 
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
 
}