刘光辉
15 小时以前 34981c30a78e8bbd7791131059a9210f9928b62c
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package jnpf.controller;
 
import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;
import jnpf.base.ActionResult;
import jnpf.base.DictionaryDataApi;
import jnpf.model.UploaderVO;
import jnpf.base.vo.DownloadVO;
import jnpf.config.ConfigValueUtil;
import jnpf.constant.FileTypeConstant;
import jnpf.constant.MsgCode;
import jnpf.entity.FileParameter;
import jnpf.service.FileService;
import jnpf.util.FileExport;
import jnpf.exception.DataException;
import jnpf.file.FileApi;
import jnpf.file.FileUploadApi;
import jnpf.model.*;
import jnpf.util.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.dromara.x.file.storage.core.FileInfo;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.*;
import java.nio.file.Files;
import java.util.*;
 
/**
 * 通用控制器
 *
 * @author JNPF开发平台组
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司(https://www.jnpfsoft.com)
 * @date 2021-03-23
 */
@Slf4j
@Tag(name = "公共", description = "file")
@RestController
@RequiredArgsConstructor
public class UtilsController implements FileApi {
 
    
    private final ConfigValueUtil configValueUtil;
    
    private final RedisUtil redisUtil;
    
    private final DictionaryDataApi dictionaryDataApi;
 
    private final FileUploadApi fileUploadApi;
    
    private final FileApi fileApi;
    
    private final FileExport fileExport;
    
    private final FileService fileService;
 
 
 
    /**
     * 图形验证码
     *
     * @return
     */
    @NoDataSourceBind
    @Operation(summary = "图形验证码")
    @GetMapping("/ImageCode/{timestamp}")
    @Parameter(name = "timestamp", description = "时间戳",required = true)
    public void imageCode(@PathVariable("timestamp") String timestamp) {
        DownUtil.downCode(null);
        redisUtil.insert(timestamp, ServletUtil.getSession().getAttribute(CodeUtil.RANDOMCODEKEY), 120);
    }
 
    /**
     * 上传文件/图片
     *
     * @return
     */
    @NoDataSourceBind
    @Operation(summary = "上传文件/图片")
    @PostMapping(value = "/Uploader/{type}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Parameter(name = "type", description = "类型",required = true)
    public ActionResult<UploaderVO> uploader(@PathVariable("type") String type, MergeChunkDto mergeChunkDto, MultipartFile file) {
        mergeChunkDto.setType(type);
        return ActionResult.success(fileService.uploadFile(mergeChunkDto, file));
    }
 
    /**
     * 图片转成base64
     *
     * @return
     */
    @NoDataSourceBind()
    @Operation(summary = "图片转成base64")
    @PostMapping(value = "/Uploader/imgToBase64", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ActionResult<Object> imgToBase64(@RequestParam("file") MultipartFile file) throws IOException {
        String encode = cn.hutool.core.codec.Base64.encode(file.getBytes());
        Object base64Name = "";
        if (StringUtil.isNotEmpty(encode)) {
            base64Name = "data:image/jpeg;base64,"+encode;
        }
        return ActionResult.success(base64Name);
    }
 
    /**
     * 获取下载文件链接
     *
     * @return
     */
    @NoDataSourceBind
    @Operation(summary = "获取下载文件链接")
    @GetMapping("/Download/{type}/{fileName}")
    @Parameter(name = "type", description = "类型",required = true)
    @Parameter(name = "fileName", description = "文件名称",required = true)
    public ActionResult<Object> downloadUrl(@PathVariable("type") String type, @PathVariable("fileName") String fileName) {
        boolean exists = FileUploadUtils.exists(new FileParameter(type, fileName));
        if (exists) {
            jnpf.base.vo.DownloadVO vo = DownloadVO.builder().name(fileName).url(UploaderUtil.uploaderFile(fileName + "#" + type)).build();
            return ActionResult.success(vo);
        }
        return ActionResult.fail(MsgCode.FA018.get());
    }
 
    /**
     * 获取全部下载文件链接(打包下载)
     *
     * @return
     */
    @NoDataSourceBind
    @Operation(summary = "获取全部下载文件链接(打包下载)")
    @PostMapping("/PackDownload/{type}")
    @Parameter(name = "type", description = "类型",required = true)
    public ActionResult packDownloadUrl(@PathVariable("type") String type, @RequestBody List<Map<String, String>> fileInfoList) throws Exception {
        if (fileInfoList == null || fileInfoList.isEmpty()) {
            return ActionResult.fail(MsgCode.FA047.get());
        }
 
        StringBuilder zipTempFilePath = null;
        String zipFileId = RandomUtil.uuId() + ".zip";
        List<String> repeatName = new ArrayList<>();
        for (Map<String, String> fileInfoMap : fileInfoList) {
            String fileId = XSSEscape.escape( fileInfoMap.get("fileId")).trim();
            String fileName = XSSEscape.escape( fileInfoMap.get("fileName")).trim();
            if (repeatName.contains(fileName)) {
                fileName = fileName.substring(0, fileName.lastIndexOf(".")) + "副本" + UUID.randomUUID().toString().substring(0, 5) + fileName.substring(fileName.lastIndexOf("."));
            } else {
                repeatName.add(fileName);
            }
            if (StringUtil.isEmpty(fileId) || StringUtil.isEmpty(fileName)) {
                continue;
            }
            FileParameter fileParameter = new FileParameter(type, fileId);
            if (FileUploadUtils.exists(fileParameter)) {
                if (zipTempFilePath == null) {
                    zipTempFilePath = new StringBuilder(FileUploadUtils.getLocalBasePath() + FilePathUtil.getFilePath(FileTypeConstant.FILEZIPDOWNTEMPPATH));
                    if (!new File(zipTempFilePath.toString()).exists()) {
                        new File(zipTempFilePath.toString()).mkdirs();
                    }
                    zipTempFilePath.append(zipFileId);
                }
                String finalZipTempFilePath = String.valueOf(zipTempFilePath);
                String finalFileName = fileName;
                FileUploadUtils.downloadFile(fileParameter, inputStream -> {
                    try {
                        ZipUtil.fileAddToZip(finalZipTempFilePath, inputStream, finalFileName);
                    } catch (Exception e) {
                        throw new IllegalArgumentException(e);
                    }
                });
            }
        }
        //将文件上传到默认文件服务器
        String newFileId = zipFileId;
        if (!"local".equals(FileUploadUtils.getDefaultPlatform())) { //不是本地,说明是其他文件服务器,将zip文件上传到其他服务器里,方便下载
            File zipFile = new File(String.valueOf(zipTempFilePath));
            FileInfo fileInfo = FileUploadUtils.uploadFile(new FileParameter(FilePathUtil.getFilePath(FileTypeConstant.FILEZIPDOWNTEMPPATH), zipFileId), zipFile);
            Files.delete(zipFile.toPath());
            FileUtils.deleteQuietly(zipFile);
            newFileId = fileInfo.getFilename();
        }
        jnpf.base.vo.DownloadVO vo = DownloadVO.builder().name(zipFileId).url(UploaderUtil.uploaderFile(newFileId + "#" + FileTypeConstant.FILEZIPDOWNTEMPPATH)).build();
        Map<String, Object> map = new HashMap<>();
        map.put("downloadVo", vo);
        map.put("downloadName", "文件" + zipFileId);
        return ActionResult.success(map);
    }
 
    /**
     * 下载文件链接
     *
     * @return
     */
    @NoDataSourceBind
    @Operation(summary = "下载文件链接")
    @GetMapping("/Download")
    public void downloadFile(@RequestParam("encryption") String encryption, @RequestParam("name") String downName) throws DataException {
        fileService.downloadFile(encryption, downName);
    }
 
 
 
 
    /**
     * 获取图片
     *
     * @param fileName
     * @param type
     * @return
     */
    @NoDataSourceBind
    @Operation(summary = "获取图片")
    @GetMapping("/Image/{type}/{fileName}")
    @Parameter(name = "type", description = "类型",required = true)
    @Parameter(name = "fileName", description = "名称",required = true)
    public void downLoadImg(@PathVariable("type") String type, @PathVariable("fileName") String fileName, @RequestParam(name = "s", required = false) String securityKey, @RequestParam(name = "t", required = false) String t) throws DataException {
        fileService.flushFile(type, fileName, securityKey, StringUtil.isEmpty(t));
    }
 
 
 
 
    /**
     * app启动获取信息
     *
     * @param appName
     * @return
     */
    @NoDataSourceBind
    @Operation(summary = "app启动获取信息")
    @GetMapping("/AppStartInfo/{appName}")
    @Parameter(name = "appName", description = "名称",required = true)
    public ActionResult<Object> getAppStartInfo(@PathVariable("appName") String appName) {
        JSONObject object = new JSONObject();
        object.put("AppVersion", configValueUtil.getAppVersion());
        object.put("AppUpdateContent", configValueUtil.getAppUpdateContent());
        return ActionResult.success(object);
    }
 
    /**
     * 大屏图片下载
     *
     * @param type
     * @param fileName
     */
    @NoDataSourceBind
    @Operation(summary = "获取图片")
    @GetMapping("/VisusalImg/{bivisualpath}/{type}/{fileName}")
    @Parameter(name = "type", description = "类型",required = true)
    @Parameter(name = "bivisualpath", description = "路径",required = true)
    @Parameter(name = "fileName", description = "名称",required = true)
    public void downVisusalImg(@PathVariable("type") String type,@PathVariable("bivisualpath") String bivisualpath, @PathVariable("fileName") String fileName) {
        fileName = XSSEscape.escapePath(fileName);
        type = XSSEscape.escapePath(type);
        String filePath = getPath(FileTypeConstant.BIVISUALPATH);
        String finalFileName = fileName;
        FileUploadUtils.downloadFile(new FileParameter(filePath + type + File.separator, fileName), inputStream ->
            FileDownloadUtil.flushFile(inputStream, finalFileName)
        );
    }
 
    @Operation(summary = "分片上传获取")
    @GetMapping("/chunk")
    public ActionResult<ChunkRes> checkChunk(Chunk chunk) {
        return ActionResult.success(fileService.checkChunk(chunk));
    }
 
 
    @Operation(summary = "分片上传附件")
    @PostMapping("/chunk")
    public ActionResult<ChunkRes> upload(Chunk chunk, MultipartFile file) {
        return ActionResult.success(fileService.uploadChunk(chunk, file));
    }
 
    @Operation(summary = "分片组装")
    @PostMapping("/merge")
    public ActionResult<UploaderVO> merge(MergeChunkDto mergeChunkDto) {
        return ActionResult.success(fileService.mergeChunk(mergeChunkDto));
    }
 
    //----------------------
 
    /**
     * 通过type获取路径
     *
     * @param type 类型
     * @return
     */
    @Override
    @NoDataSourceBind()
    @GetMapping("/getPath/{type}")
    public String getPath(@PathVariable("type") String type) {
        return fileService.getPath(type);
    }
 
    /**
     * 导出
     *
     * @param exportModel
     * @return
     */
    @Override
    @NoDataSourceBind
    @PostMapping("/export")
    public jnpf.base.vo.DownloadVO exportFile(@RequestBody ExportModel exportModel) {
        return fileExport.exportFile(exportModel.getClazz(), exportModel.getFilePath(), exportModel.getFileName(), exportModel.getTableName());
    }
 
    /**
     * 获取代码生成器默认保存路径
     *
     * @return
     */
    @Override
    @NoDataSourceBind()
    @GetMapping("/getLocalBasePath")
    public String getLocalBasePath() {
        return fileService.getLocalBasePath();
    }
 
 
 
    /**
     * 获取允许文件预览类型
     *
     * @return
     */
    @Override
    @NoDataSourceBind()
    @GetMapping("/getAllowPreviewFileType")
    public String getAllowPreviewFileType() {
        return configValueUtil.getAllowPreviewFileType();
    }
 
    @Override
    @NoDataSourceBind()
    @GetMapping("/fileExists")
    public Boolean fileExists(@RequestParam("type") String path, @RequestParam("fileName") String fileName) {
        return fileService.fileExists(path, fileName);
    }
 
    @Operation(summary = "预览文件")
    @GetMapping("/Uploader/Preview")
    public ActionResult<Object> preview(PreviewParams previewParams) {
        return ActionResult.success(MsgCode.SU000.get(), fileService.previewFile(previewParams));
    }
 
}