yanghb
2024-12-17 1287337fd0b0c156ec79712f9a600ebeffefe3a6
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
package com.zzg.system.service.system.impl;
 
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.IdUtil;
import com.zzg.common.constant.SysConstants;
import com.zzg.common.exception.GlobalException;
import com.zzg.common.utils.DateUtil;
import com.zzg.common.utils.FileUtil;
import com.zzg.common.utils.ZZGFileUtil;
import com.zzg.system.domain.AttachFile;
import com.zzg.system.service.system.IFileService;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
 
@Service
@Slf4j
@EnableScheduling
public class FileServiceImpl implements IFileService {
 
    @Value("${ruoyi.upload}")
    private String uploadPath;
    @Value("${ruoyi.temp}")
    private String tempPath;
    @Value("${ruoyi.template}")
    private String template;
 
//    @Resource
//    DrawingsMapper drawingsMapper;
 
    @Override
    public void saveFile(@NonNull InputStream inputStream, @NonNull File file) {
        try {
            FileUtils.copyInputStreamToFile(inputStream, file);
        } catch (IOException e) {
            log.error("保存文件失败!!!", e);
            throw new RuntimeException("文件保存失败", e);
        }
    }
 
    @Override
    public void saveFile(@NonNull InputStream inputStream, @NonNull String filename) {
        saveFile(inputStream, new File(filename));
    }
 
    @Override
    public String upload2Temp(@NonNull MultipartFile multipartFile, HttpServletRequest req) {
        try {
            // IE浏览器获取的"originalFileName"带盘符,此处不能直接用
            String originalFileName = multipartFile.getOriginalFilename();
            // 截取真实文件名,解决浏览器兼容性问题
            String fileName = originalFileName.substring(originalFileName.lastIndexOf('\\') + 1);
            String path = tempPath + DateUtil.transDateToStr(new Date()) + "/" + IdUtil.fastSimpleUUID() + "/" + fileName;
            saveFile(multipartFile.getInputStream(), path);
            return path;
        } catch (IOException e) {
            log.error("保存文件失败!", e);
            throw new RuntimeException("保存文件失败", e);
        }
    }
 
    @Override
    public List<Dict> upload2Temp(@NonNull List<MultipartFile> multipartFiles, HttpServletRequest req) {
        Objects.requireNonNull(multipartFiles, "上传文件为空!");
        // 文件保存方法
        //此处文件已经保存
        Function<MultipartFile, Dict> getInputStream = a -> {
            long size = a.getSize();
            if (size > 200 * 1024 * 1024) {
                throw new RuntimeException("上传的单个文档不能大于200M");
            }
            String suffix = FileUtil.getSuffix(a.getOriginalFilename());
            String[] suffixArray = {"shp", "cpg", "dbf", "prj", "sbn", "sbx", "xml", "shx"};
            if (!Arrays.asList(suffixArray).contains(suffix)) {
                // 将以上后缀名的文件都略过校验
                try {
                    boolean b = FileUtil.CheckFileHead((FileInputStream) a.getInputStream());
                    if (!b) {
                        throw new RuntimeException("文件格式异常!");
                    }
                } catch (IOException e) {
                    throw new RuntimeException("文件校验异常!", e);
                }
            }
 
            // IE浏览器获取的"originalFileName"带盘符,此处不能直接用
            String originalFileName = a.getOriginalFilename();
 
            try {
                Dict dict = new Dict();
                // 截取真实文件名,解决浏览器兼容性问题
                String fileName = originalFileName.substring(originalFileName.lastIndexOf('\\') + 1);
                String path = DateUtil.transDateToStr(new Date()) + "/" + ZZGFileUtil.getUUIDFileName(fileName);
                saveFile(a.getInputStream(), tempPath + path);
                dict.put("path", SysConstants.Path.TEMP + "/" + path);
                dict.put("fileName", fileName);
                return dict;
            } catch (IOException e) {
                throw new RuntimeException("获取上传文件输入流失败!", e);
            }
        };
 
//        List<Dict> list = multipartFiles.parallelStream().map(getInputStream).collect(Collectors.toList());
//        List<String> tempList = list.stream().map(new Function<String, String>() {
//            @Override
//            public String apply(String s) {
//                s = SysConstants.Path.TEMP + "/" + s;
//                return s;
//            }
//        }).collect(Collectors.toList());
 
        return multipartFiles.parallelStream().map(getInputStream).collect(Collectors.toList());
    }
 
 
    @Override
    public void moveFile(String sourcePath, String destPath) {
        try {
            sourcePath = tempPath + sourcePath;
            destPath = uploadPath + destPath;
 
            // 将字符串路径转换为Path对象
            Path source = Paths.get(sourcePath);
            Path dest = Paths.get(destPath);
            // 确保目标目录存在,如果不存在则创建
            if (!Files.exists(dest.getParent())) {
                Files.createDirectories(dest.getParent());
            }
 
            // 将文件从源路径移动到目标路径
            Files.move(source, dest);
        } catch (IOException e) {
            e.printStackTrace();
            System.err.println("Failed to move file: " + e.getMessage());
        }
    }
 
    @Override
    public void deleteFile(String filePath) {
        try {
            filePath = uploadPath + filePath;
            // 将字符串路径转换为Path对象
            Path file = Paths.get(filePath);
            // 如果文件存在,则删除它
            if (Files.exists(file)) {
                Files.delete(file);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    @Override
    public List<String> uploadFile2uploadPath(List<MultipartFile> fileList) {
        Objects.requireNonNull(fileList, "上传文件为空!");
        // 文件保存方法
        //此处文件已经保存
        Function<MultipartFile, String> getInputStream = a -> {
            long size = a.getSize();
            if (size > 20 * 1024 * 1024) {
                throw new RuntimeException("上传的单个文档不能大于20M");
            }
            String suffix = FileUtil.getSuffix(a.getOriginalFilename());
            String[] suffixArray = {"shp", "cpg", "dbf", "prj", "sbn", "sbx", "xml", "shx"};
            if (!Arrays.asList(suffixArray).contains(suffix)) {
                // 将以上后缀名的文件都略过校验
                try {
                    boolean b = FileUtil.CheckFileHead((FileInputStream) a.getInputStream());
                    if (!b) {
                        throw new RuntimeException("文件格式异常!");
                    }
                } catch (IOException e) {
                    throw new RuntimeException("文件校验异常!", e);
                }
            }
 
            // IE浏览器获取的"originalFileName"带盘符,此处不能直接用
            String originalFileName = a.getOriginalFilename();
            try {
                // 截取真实文件名,解决浏览器兼容性问题
                String fileName = originalFileName.substring(originalFileName.lastIndexOf('\\') + 1);
                String path = ZZGFileUtil.getUUIDFileName(fileName);
                saveFile(a.getInputStream(), uploadPath + path);
                return path;
            } catch (IOException e) {
                throw new RuntimeException("获取上传文件输入流失败!", e);
            }
        };
 
        List<String> list = fileList.parallelStream().map(getInputStream).collect(Collectors.toList());
 
        List<String> filePathList = list.stream().map(new Function<String, String>() {
            @Override
            public String apply(String s) {
                s = SysConstants.Path.UPLOAD + "/" + s;
                return s;
            }
        }).collect(Collectors.toList());
        return filePathList;
    }
 
//    @Override
//    public List<String> uploadFile(List<MultipartFile> fileList) {
//        Objects.requireNonNull(fileList, "上传文件为空!");
//        // 文件保存方法
//        //此处文件已经保存
//        Function<MultipartFile, String> getInputStream = a -> {
//
//            // IE浏览器获取的"originalFileName"带盘符,此处不能直接用
//            String originalFileName = a.getOriginalFilename();
//            try {
//                // 截取真实文件名,解决浏览器兼容性问题
//                String fileName = originalFileName.substring(originalFileName.lastIndexOf('\\') + 1);
//                String path = ZZGFileUtil.getUUIDFileName(fileName);
//                saveFile(a.getInputStream(), uploadPath + path);
//                return path;
//            } catch (IOException e) {
//                throw new RuntimeException("获取上传文件输入流失败!", e);
//            }
//        };
//
//        List<String> list = fileList.parallelStream().map(getInputStream).collect(Collectors.toList());
//
//        List<String> filePathList = list.stream().map(new Function<String, String>() {
//            @Override
//            public String apply(String s) {
//                s = SysConstants.Path.UPLOAD + "/" + s;
//                return s;
//            }
//        }).collect(Collectors.toList());
//        return filePathList;
//    }
 
//    @Override
//    public void downloadFile(@NonNull List<String> fileNames) throws IOException {
 
 
//        if (fileNames.isEmpty()) {
//            throw new RequestException("至少下载一个文件!");
//        }
//        // 根据文件路径前缀,拼接真实路径
//        Function<String, String> judgeCatalogue = str -> {
//            String identity = str.substring(0, str.indexOf("/"));
//            boolean b = RegExpValidatorUtils.isDate(identity);
//            if (b) {
//                str = tempPath + str;
//            }else {
//                str = uploadPath + str;
//            }
//            return str;
//        };
//        List<String> fileNames_judege = fileNames.stream().map(judgeCatalogue).collect(Collectors.toList());
//        if (1 == fileNames.size()) {
//            ZZGFileUtil.outFile(new File(fileNames_judege.get(0)), fileNames_judege.get(0));
//        } else {
//            HttpServletResponse response = RequestHolder.getResponse();
//            ZZGFileUtil.setOutFileHeader(response, fileNames_judege.get(0) + ".zip", null);
//            ZipOutputStream outputStream = new ZipOutputStream(response.getOutputStream());
//            ZZGFileUtil.copyZipOut(outputStream,
//                    fileNames_judege.stream().map(a -> a).map(File::new).toArray(File[]::new));
//            outputStream.finish();
//        }
//    }
 
    /**
     * 单个文件下载
     *
     * @param filePath 文件绝对路
     */
//    public void download(String filePath, HttpServletResponse response) throws IOException {
//        File absFile = new File(filePath);
//        if (absFile.exists()) {
//            response.setContentType("application/octet-stream;charset=utf-8");
//            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(cn.hutool.core.io.FileUtil.getName(absFile), "UTF-8"));
//            FileInputStream fileInputStream = new FileInputStream(absFile);
//            int len = 0;
//            byte[] buffer = new byte[1024];
//            OutputStream outputStream = response.getOutputStream();
//            while ((len = fileInputStream.read(buffer)) > 0) {
//                outputStream.write(buffer, 0, len);
//            }
//            fileInputStream.close();
//            outputStream.flush();
//            outputStream.close();
//        } else {
//            throw new CustomException(CustomExceptionEnums.FILES_NOT_FOUND_ERROR);
//        }
//    }
 
 
    /**
     * 将指定文件从临时目录复制到持久目录
     *
     * @throws IOException
     */
    @Override
    public void synFiles(@NonNull List<String> fileNames, @NonNull String destDir) throws IOException {
        List<File> files = fileNames.stream().map(File::new).collect(Collectors.toList());
        File destFile = new File(destDir);
        if (!destFile.exists()) {
            boolean bool = destFile.mkdirs();
            if (!destFile.isDirectory() || !bool) {
                throw new IllegalAccessError("目录:" + destDir + "创建失败!");
            }
        }
        FileUtils.copyToDirectory(files, destFile);
    }
 
    /**
     * 将选择的文件同步到upload路径下
     *
     * @param fileNames 文件
     * @throws IOException
     */
    @Override
    public void synFiles2Upload(List<String> fileNames) throws IOException {
        File destFile = new File(uploadPath);
        if (!destFile.exists()) {
            boolean bool = destFile.mkdirs();
            if (!destFile.isDirectory() || !bool) {
                throw new IllegalAccessError("目录:" + uploadPath + "创建失败!");
            }
        }
//        List<File> files = fileNames.stream().map(File::new).collect(Collectors.toList());
        List<File> files = new ArrayList<>();
        for (String path : fileNames) {
            if (!path.contains(uploadPath)) {
                files.add(new File(path));
            }
        }
        if (files.size() > 0) {
            FileUtils.copyToDirectory(files, destFile);
        }
    }
 
 
    /**
     * 将选择的文件同步到upload路径下(去除日期)
     *
     * @param fileNames 文件
     * @throws IOException
     */
    @Override
    public List<File> synFiles2UploadMoveDate(List<String> fileNames) throws IOException {
        File destFile = new File(uploadPath);
        if (!destFile.exists()) {
            boolean bool = destFile.mkdirs();
            if (!destFile.isDirectory() || !bool) {
                throw new IllegalAccessError("目录:" + uploadPath + "创建失败!");
            }
        }
//        List<File> files = fileNames.stream().map(File::new).collect(Collectors.toList());
        List<File> files = new ArrayList<>();
        for (String path : fileNames) {
            String sourcePath = path;
            String separator = File.separator;
            path = path.replace("\\", separator);
            path = path.replace("/", separator);
            // 获取 `\` 和 `_` 之间的字符串
            int startIndex = path.lastIndexOf(File.separator) + 1;
            int endIndex = path.indexOf("_");
            String result = path.substring(startIndex, endIndex + 1);
 
            // 删除文件名前面的自定义uuid
            String targetPath = path.replace(result, "");
 
            // 文件复制
            try {
                FileUtil.copy(sourcePath, targetPath);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
 
            if (!targetPath.contains(destFile.getAbsolutePath())) {
                files.add(new File(targetPath));
            }
        }
 
        if (files.size() > 0) {
            FileUtils.copyToDirectory(files, destFile);
        }
        return files;
    }
 
    @Override
    public void synFiles2Upload(Map<String, String> fileNames) throws IOException {
        File destFile = new File(uploadPath);
        if (!destFile.exists()) {
            boolean bool = destFile.mkdirs();
            if (!destFile.isDirectory() || !bool) {
                throw new IllegalAccessError("目录:" + uploadPath + "创建失败!");
            }
        }
        List<File> files = new ArrayList<>();
        for (Map.Entry<String, String> e : fileNames.entrySet()) {
            if (!e.getValue().contains(destFile.getAbsolutePath())) {
                files.add(new File(e.getValue()));
            }
        }
        if (files.size() > 0) {
            FileUtils.copyToDirectory(files, destFile);
        }
    }
 
    /**
     * 保存文件目录的创建!
     */
//    @PostConstruct
//    public void createFilepath() {
//        File file = new File(uploadPath);
//        if (!file.exists()) {
//            file.mkdirs();
//            if (!file.isDirectory()) {
//                throw new IllegalAccessError("系统保存文件的位置应该是一个可创建的目录!目录:" + uploadPath + "创建失败!");
//            }
//        }
//        File file2 = new File(tempPath);
//        if (!file2.exists()) {
//            file2.mkdirs();
//            if (!file2.isDirectory()) {
//                throw new IllegalAccessError("系统保存文件的位置应该是一个可创建的目录!目录:" + tempPath + "创建失败!");
//            }
//        }
//    }
 
    /**
     * 每天晚上12:00删除临时目录里面的过期文件,保存最近七天的文件
     * <p>
     */
    /*@Scheduled(cron = "00 00 00 * * ?")
    @Override
    public void refreshTemp() {
//        File tempFile = new File(tempPath);
//        // 获取临时目录中的所有文件夹
//        Collection<File> listFilesAndDirs = FileUtils.listFilesAndDirs(tempFile, FalseFileFilter.INSTANCE, TrueFileFilter.INSTANCE);
//        // 排除临时目录自身
//        listFilesAndDirs.remove(tempFile);
//        for (File file : listFilesAndDirs) {
//            if (DateUtil.daysBetween(DateUtil.transStrToDate(file.getName()), new Date()) > 7) {
//                log.info("定时删除临时文件夹:" + file.getAbsolutePath());
//                FileUtils.deleteQuietly(file);
//            }
//        }
//    }
 
    }*/
 
    /*@Override
    public String upload2Word(List<MultipartFile> multipartFiles, HttpServletRequest req) {
        Objects.requireNonNull(multipartFiles, "上传文件为空!");
        // 文件保存方法
        //此处文件已经保存
        Function<MultipartFile, String> getInputStream = a -> {
            try {
                // IE浏览器获取的"originalFileName"带盘符,此处不能直接用
                String originalFileName = a.getOriginalFilename();
                // 截取真实文件名,解决浏览器兼容性问题
                String fileName = originalFileName.substring(originalFileName.lastIndexOf('\\') + 1);
                String path = DateUtil.transDateToStr(new Date()) + "/" + ZZGFileUtil.getUUIDFileName(fileName);
                saveFile(a.getInputStream(), tempPath + path);
                return path;
            } catch (IOException e) {
                throw new RuntimeException("获取上传文件输入流失败!", e);
            }
        };
//        List<String> collect = multipartFiles.parallelStream().map(MultipartFile::getOriginalFilename).collect(Collectors.toList());
 
        List<String> list = multipartFiles.parallelStream().map(getInputStream).collect(Collectors.toList());
 
 
        List<String> tempList = list.stream().map(new Function<String, String>() {
            @Override
            public String apply(String s) {
                s = SysConstants.Path.TEMP + "/" + s;
                String last = s.substring(s.lastIndexOf(".") + 1);
                if (last.equals("doc") || last.equals("docx")) {
                    s = wordService.wordToPdf(s);
                }
                return s;
            }
        }).collect(Collectors.toList());
 
        return JSONArray.toJSONString(tempList);
    }*/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer uploadTemplateFile(String projectId, Integer noticeType, MultipartFile multipartFile) {
//        File tempPath = new File(template);
//        if (!tempPath.exists()) {
//            tempPath.mkdirs();
//        }
//        String originalFileName = multipartFile.getOriginalFilename();
//        String fileName = originalFileName.substring(originalFileName.lastIndexOf('\\') + 1);
//        String file = ZZGFileUtil.getUUIDFileName(fileName);
//        try {
//            FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), new File(tempPath + File.separator + file));
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//        //查询是否已有此模板数据
//        Drawings drawings = drawingsMapper.selectOne(new LambdaQueryWrapper<Drawings>()
//                .eq(Drawings::getProjectId, projectId)
//                .eq(Drawings::getImageType, "公告模板")
//                .eq(Drawings::getImagePersona, noticeType));
//
//        if (drawings == null) {
//            drawings = new Drawings();
//            drawings.setProjectId(projectId);
//            drawings.setImageType("公告模板");
//            drawings.setImagePersona(noticeType.toString());
//            drawings.setCreateTime(new Date());
//            drawings.setCreateName(SecurityUtils.getUsername());
//        }
//        drawings.setUrl("template" + File.separator + file);
//        drawings.setOriginal(originalFileName);
//
//        int a;
//        if (drawings.getId() != null) {
//            a = drawingsMapper.updateById(drawings);
//        } else {
//            a = drawingsMapper.insert(drawings);
//        }
        return 1;
    }
 
    @Override
    public void upload2uploadPath(List<AttachFile> familyAttachFiles) {
        for (AttachFile attachFile : familyAttachFiles) {
            String filePath = attachFile.getFilePath();
            try {
                FileInputStream file = new FileInputStream(filePath);
                String path = uploadPath + "/" + IdUtil.fastSimpleUUID() + "_" + filePath.substring(filePath.lastIndexOf("/") + 1);
                saveFile(file, path);
                //更新路径
                attachFile.setFilePath(path);
            } catch (FileNotFoundException e) {
                throw new GlobalException("文件不存在!");
            } catch (IOException e) {
                log.error("保存文件失败!", e);
                throw new RuntimeException("保存文件失败", e);
            }
        }
    }
 
 
    /**
     * 获取模板文件的真实路径
     *
     * @return 模板文件真实路径
     */
    public String getTemplateFilePath() {
        return template;
    }
 
    /**
     * 获取临时文件的真实路径
     *
     * @return 模板文件真实路径
     */
    public String getTempFilePath() {
        return tempPath;
    }
 
    /**
     * 获取下载文件的真实路径
     *
     * @return 模板文件真实路径
     */
    public String getUploadFilePath() {
        return uploadPath;
    }
 
 
}