jinlin
2024-02-21 b27d06b8f0b805efd16e28fd80a57a0ed8a053ce
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
253
254
255
/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有,侵权必究!
 */
 
package com.zt.modules.oss.cloud;
 
import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.spire.xls.Workbook;
import com.zt.common.exception.ErrorCode;
import com.zt.common.exception.RenException;
import com.zt.core.oss.encry.IOssEncryptService;
import com.zt.modules.oss.enums.CloudChannel;
import com.zt.modules.oss.model.QdSysOss;
import com.zt.modules.oss.model.SysOss;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
 
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
 
/**
 * 本地上传
 *
 * @author hehz
 */
 
public class LocalStorageService extends AbstractStorageService {
 
    private IOssEncryptService ossEncryptService;
 
    public LocalStorageService(StorageConfig config, QdStorageConfig qdConfig, IOssEncryptService ossEncryptService) {
        this.config = config;
        this.qdConfig = qdConfig;
        this.ossEncryptService = ossEncryptService;
    }
 
    @Override
    public SysOss upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }
 
    @Override
    public SysOss upload(InputStream inputStream, String path) {
        File file = new File(config.getLocalPath() + File.separator + path);
        try {
            FileUtils.copyToFile(ossEncryptService.encrypt(inputStream), file);
        } catch (IOException e) {
            throw new RenException(ErrorCode.OSS_UPLOAD_FILE_ERROR.getCode(), e, "");
        }
 
        SysOss oss = new SysOss();
        oss.setId(IdWorker.getId());
        oss.setPath(path);
        oss.setUrl(config.getLocalDomain() + "/sys/oss/content");
        return oss;
    }
 
    @Override
    public SysOss uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(config.getLocalPrefix(), suffix));
    }
 
    @Override
    public SysOss uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(config.getLocalPrefix(), suffix));
    }
 
    @Override
    public void delete(SysOss oss) {
        if (oss != null) {
            File file = new File(config.getLocalPath() + File.separator + oss.getPath());
            if (file.exists()) {
                File dir = file.getParentFile();
                try {
                    if (dir.listFiles().length == 1) {
                        FileUtils.forceDelete(dir);
                    } else {
                        FileUtils.forceDelete(file);
                    }
                } catch (IOException e) {
                    throw new RenException("本地文件删除失败!");
                }
            }
        }
    }
 
    public void content(SysOss oss, HttpServletResponse response) throws Exception {
        if (oss == null) {
            throw new IOException("文件不存在!");
        }
        if (CloudChannel.LOCAL.getValue().equals(oss.getChannel())) { // 本地
            String filename = oss.getName();
            if (",gif,jpg,jpeg,png,bmp,".contains("," + oss.getType() + ",")) {// 浏览图片
                response.setContentType("image/jpeg");
            } else {
                response.setContentType("application/octet-stream");
//                response.setHeader("Content-disposition",
//                        "attachment;filename=" + new String(filename.getBytes("ISO8859-1"), "UTF-8"));
                response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            }
            File file = new File(config.getLocalPath() + File.separator + oss.getPath());
            System.out.println(config.getLocalPath());
            System.out.println(File.separator);
            System.out.println(oss.getPath());
            // 创建文件输入流
            InputStream is = ossEncryptService.decrypt(file);
            // 响应输出流
            ServletOutputStream out = response.getOutputStream();
            // 创建缓冲区
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            is.close();
            out.flush();
            out.close();
        }
    }
 
    public ResponseEntity<byte[]> content2(SysOss oss) throws Exception {
        if (oss == null) {
            throw new IOException("文件不存在!");
        }
        if (CloudChannel.LOCAL.getValue().equals(oss.getChannel())) { // 本地
            String filename = oss.getName();
            File file = new File(config.getLocalPath() + File.separator + oss.getPath());
            if (file.exists()) {
                try (InputStream in = ossEncryptService.decrypt(file)) {
                    // 从文件输入流中读取Word文档的二进制数据并存储在documentBytes数组中
                    byte[] documentBytes = new byte[0];
                    // 创建HTTP头部,设置内容类型为二进制流,并指定文件名
                    HttpHeaders headers = new HttpHeaders();
                    // 返回包含二进制数据流的HTTP响应,状态码为200
                    if (filename.endsWith(".xls")) {
                        // 如果是xls文件,将其转换为xlsx格式
                        Workbook workbook = new Workbook();
                        workbook.loadFromStream(in); // 使用loadFromStream方法加载xls文件
                        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                        workbook.saveToStream(outputStream, com.spire.xls.FileFormat.Version2013); // 指定文件格式
                        documentBytes = outputStream.toByteArray();
                        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                    }
 
                    if (filename.endsWith(".doc")) {
                        // 使用 Aspose.Words 进行文档转换
                        Document doc = new Document(in);
                        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                        doc.save(outputStream, SaveFormat.DOCX);
 
                        documentBytes = outputStream.toByteArray();
                        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                        headers.setContentDispositionFormData("attachment", filename.replace(".doc", ".docx"));
                    } else if (filename.endsWith(".docx") || filename.endsWith(".xlsx")) {
                        documentBytes = FileCopyUtils.copyToByteArray(in);
                        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                        headers.setContentDispositionFormData("attachment", filename);
                    } else if (filename.endsWith(".pdf")) {
                        documentBytes = FileCopyUtils.copyToByteArray(in);
                        headers.setContentType(MediaType.APPLICATION_PDF);
                    } else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg")) {
                        documentBytes = FileCopyUtils.copyToByteArray(in);
                        headers.setContentType(MediaType.IMAGE_JPEG);
                    } else if (filename.endsWith(".png")) {
                        documentBytes = FileCopyUtils.copyToByteArray(in);
                        headers.setContentType(MediaType.IMAGE_PNG);
                    }
                    return new ResponseEntity<>(documentBytes, headers, HttpStatus.OK);
                }
            } else {
                String errorMessage = "文件不存在";
                return new ResponseEntity<>(errorMessage.getBytes(), HttpStatus.NOT_FOUND);
            }
        }
        String errorMessage = "文件不存在";
        return new ResponseEntity<>(errorMessage.getBytes(), HttpStatus.NOT_FOUND);
    }
 
    public void getCommFile(String fileFlag, HttpServletResponse response) throws Exception {
        if (fileFlag == null) {
            throw new IOException("图片不存在!");
        }
        if ("logo".contains(fileFlag)) {// 浏览图片
            response.setContentType("image/jpeg");
        } else {
            response.setContentType("application/octet-stream");
//                response.setHeader("Content-disposition",
//                        "attachment;filename=" + new String(filename.getBytes("ISO8859-1"), "UTF-8"));
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileFlag, "UTF-8"));
        }
        String url = config.getLocalPath() + File.separator + "comm-file" + File.separator + fileFlag;
        File file = new File(url);
        System.out.println(url);
        // 创建文件输入流
        InputStream is = ossEncryptService.decrypt(file);
        // 响应输出流
        ServletOutputStream out = response.getOutputStream();
        // 创建缓冲区
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = is.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        out.flush();
        out.close();
 
    }
 
    public void qdContent(QdSysOss qdSysOss, HttpServletResponse response) throws Exception {
        if (qdSysOss == null) {
            throw new IOException("文件不存在!");
        }
        if (CloudChannel.LOCAL.getValue().equals(qdSysOss.getChannel())) { // 本地
            String filename = qdSysOss.getName();
            if (",gif,jpg,jpeg,png,bmp,".contains("," + qdSysOss.getType() + ",")) {// 浏览图片
                response.setContentType("image/jpeg");
            } else {
                response.setContentType("application/octet-stream");
//                response.setHeader("Content-disposition",
//                        "attachment;filename=" + new String(filename.getBytes("ISO8859-1"), "UTF-8"));
                response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            }
            File file = new File(qdConfig.getQdLocalPath() + File.separator + qdSysOss.getPath());
            System.out.println("qd:" + qdConfig.getQdLocalPath());
            System.out.println("qd:" + File.separator);
            System.out.println("qd:" + qdSysOss.getPath());
            // 创建文件输入流
            InputStream is = ossEncryptService.decrypt(file);
            // 响应输出流
            ServletOutputStream out = response.getOutputStream();
            // 创建缓冲区
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            is.close();
            out.flush();
            out.close();
        }
    }
}