月球大数据地理空间分析展示平台-【后端】-月球后台服务
13693261870
2023-06-02 c31e03f0e51214a524d3fc34d30f3459698ff625
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
package com.moon.server.service.all;
 
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.moon.server.controller.all.BaseController;
import com.moon.server.entity.all.ResponseMsg;
import com.moon.server.entity.all.SettingData;
import com.moon.server.entity.ctrl.KeyValueEntity;
import com.moon.server.entity.data.DownloadEntity;
import com.moon.server.entity.data.MetaEntity;
import com.moon.server.entity.data.MetaFileEntity;
import com.moon.server.entity.sys.AttachEntity;
import com.moon.server.entity.sys.UserEntity;
import com.moon.server.mapper.all.BasicMapper;
import com.moon.server.mapper.data.DownloadMapper;
import com.moon.server.service.sys.AttachService;
import com.moon.server.entity.all.BaseEntity;
import com.moon.server.entity.all.StaticData;
import com.moon.server.helper.*;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.model.FileHeader;
import net.lingala.zip4j.model.ZipParameters;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.lang.reflect.Field;
import java.util.*;
 
/**
 * 上传附件服务类
 * @author WWW
 */
@Service
public class UploadAttachService {
    @Autowired
    PathHelper pathHelper;
 
    @Autowired
    AttachService attachService;
 
    @Autowired
    DownloadMapper downloadMapper;
 
    private static String tabs = "''";
 
    public final static Map<String, String> ATTACH_TABS = new HashMap<>();
 
    private final static Log log = LogFactory.getLog(UploadAttachService.class);
 
    /**
     * 获取表名
     */
    public static String getTabs() {
        return tabs;
    }
 
    /**
     * 初始化附件表
     */
    public static void init(String cfg) {
        if (StringHelper.isEmpty(cfg)) {
            return;
        }
 
        String[] strs = cfg.split(StaticData.COMMA);
        if (strs.length == 0) {
            return;
        }
 
        List<String> keys = new ArrayList<>();
        for (String str : strs) {
            if (ATTACH_TABS.containsKey(str)) {
                continue;
            }
 
            ATTACH_TABS.put(str, str.contains("bd.") ? "materiname" : "photono");
            keys.add("'" + str + "'");
        }
        tabs = StringHelper.join(keys, ",");
    }
 
    /**
     * 上传文件
     */
    public ResponseMsg<String> upload(UserEntity ue, String tab, MultipartFile file, BaseController ctrl) {
        try {
            if (file == null && file.isEmpty()) {
                return ctrl.fail("文件上传为空", null);
            }
            if (file.getSize() > SettingData.MAX_FILE_SIZE) {
                return ctrl.fail(String.format("文件大于 %d MB", SettingData.MAX_FILE_SIZE / 1024 / 1024), null);
            }
 
            // 传输文件
            String oldName = file.getOriginalFilename();
            String filePath = pathHelper.getTempPath() + File.separator + oldName;
            File newFile = new File(filePath);
            file.transferTo(newFile);
            double sizes = FileHelper.sizeToMb(file.getSize());
 
            // 获取MD5
            String md5 = FileHelper.getFileMd5(filePath);
            AttachEntity entity = attachService.selectByGuid(md5);
            if (entity != null) {
                newFile.delete();
                return ctrl.success("文件已存在", md5);
            }
 
            AttachEntity ae = getAttachEntity(ue, tab, oldName, md5, sizes);
            String targetPath = pathHelper.getConfig().getUploadPath() + File.separator + ae.getPath();
            newFile.renameTo(new File(targetPath));
 
            int rows = attachService.insert(ae);
 
            return rows > 0 ? ctrl.success(md5) : ctrl.fail("保存文件失败", null);
        } catch (Exception ex) {
            return ctrl.fail(ex.getMessage(), null);
        }
    }
 
    /**
     * 获取附件实体类
     */
    protected AttachEntity getAttachEntity(UserEntity ue, String tab, String oldName, String md5, double sizes) {
        AttachEntity entity = new AttachEntity();
        entity.setName(oldName);
        entity.setTab(tab);
        entity.setGuid(md5);
        String subPath = PathHelper.getUploadPath() + File.separator + md5 + FileHelper.getExtension(oldName);
        entity.setPath(subPath);
        entity.setSizes(sizes);
        if (ue != null) {
            entity.setCreateUser(ue.getId());
        }
 
        return entity;
    }
 
    /**
     * 下载文件
     */
    public void download(String guid, HttpServletResponse res) {
        download(guid, false, res);
    }
 
    /**
     * 下载文件
     */
    public void download(String guid, boolean inline, HttpServletResponse res) {
        try {
            if (StringHelper.isEmpty(guid)) {
                WebHelper.writeStr2Page(res, StaticData.NO_FILE);
                return;
            }
 
            AttachEntity entity = attachService.selectByGuid(guid);
            if (entity == null) {
                WebHelper.writeStr2Page(res, StaticData.NO_FILE);
                return;
            }
 
            String filePath = pathHelper.getConfig().getUploadPath() + File.separator + entity.getPath();
            File file = new File(filePath);
            if (!file.exists() || file.isDirectory()) {
                WebHelper.writeJson2Page(res, "文件不存在");
            }
 
            WebHelper.download(filePath, entity.getName(), inline, res);
        } catch (Exception ex) {
            WebHelper.writeJson2Page(res, "文件下载出错");
            log.error(ex.getMessage(), ex);
        }
    }
 
    /**
     * 上传Excel附件
     */
    public List<KeyValueEntity> uploadXlsAnnex(UserEntity ue, List<MetaEntity> ms, List<MetaFileEntity> list, String path) {
        List<String> files = getAttachFiles(list, path);
        if (files.size() == 0) {
            return null;
        }
 
        List<KeyValueEntity> rs = new ArrayList<>();
        for (MetaEntity meta : ms) {
            int rows = uploadXlsAnnex(ue, meta, files);
            rs.add(new KeyValueEntity(meta.getName(), String.valueOf(rows)));
        }
 
        return rs;
    }
 
    /**
     * 获取附件文件
     */
    private List<String> getAttachFiles(List<MetaFileEntity> list, String path) {
        List<String> files = new ArrayList<>();
 
        for (MetaFileEntity mf : list) {
            if (mf.getName().contains(StaticData.ZIP)) {
                List<String> subs = getZipFiles(mf, path);
                if (null != subs && subs.size() > 0) {
                    files.addAll(subs);
                }
                continue;
            }
 
            files.add(mf.getPath());
        }
 
        return files;
    }
 
    /**
     * 获取zip中的文件
     */
    private List<String> getZipFiles(MetaFileEntity mf, String path) {
        File file = new File(mf.getPath());
        if (!file.exists() || file.isDirectory()) {
            return null;
        }
 
        File zipFolder = new File(pathHelper.getConfig().getTempPath() + File.separator + path + "_zip");
        if (!zipFolder.exists() || !zipFolder.isDirectory()) {
            zipFolder.mkdirs();
        }
 
        String subPath = zipFolder + File.separator + mf.getName().toLowerCase().replace(".zip", "");
        ZipHelper.unzip(mf.getPath(), subPath);
 
        List<String> files = new ArrayList<>();
        getFilesByPath(files, subPath);
 
        return files;
    }
 
    /**
     * 根据路径获取文件
     */
    private void getFilesByPath(List<String> list, String path) {
        File file = new File(path);
        if (!file.isDirectory()) {
            list.add(file.getPath());
            return;
        }
 
        File[] files = file.listFiles();
        if (null == files) {
            return;
        }
 
        for (File f : files) {
            if (f.isDirectory()) {
                getFilesByPath(list, f.getPath());
            } else {
                list.add(f.getPath());
            }
        }
    }
 
    /**
     * 上传Excel附件
     */
    private int uploadXlsAnnex(UserEntity ue, MetaEntity meta, List<String> files) {
        List<?> list = queryXlsData(meta);
        if (null == list || list.size() == 0) {
            return 0;
        }
 
        Field field = getAnnexField(list.get(0), meta.getTab());
        String folder = meta.getName().split("\\.")[0].trim().toLowerCase() + File.separator;
 
        int rows = 0;
        for (Object obj : list) {
            String[] names = getNames(getAnnexName(obj, field));
            if (null == names || names.length == 0) {
                continue;
            }
 
            for (String name : names) {
                String file = findAnnexFile(name, folder, files);
                if (null == file) {
                    continue;
                }
 
                rows += insertXlsAnnex(ue, meta, (BaseEntity) obj, file);
            }
        }
 
        return rows;
    }
 
    /**
     * 获取名称
     */
    public static String[] getNames(String str) {
        if (StringHelper.isEmpty(str)) {
            return null;
        }
 
        return str.replace(";", ",").replace(",", ",").split(",");
    }
 
    /**
     * 查询Excel数据
     */
    private List<?> queryXlsData(MetaEntity meta) {
        String entity = meta.getTab().substring(meta.getTab().indexOf(".") + 1).replace("_", "").toLowerCase();
        BasicMapper basicMapper = ClassHelper.getBasicMapper(entity);
        if (null == basicMapper) {
            return null;
        }
 
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("parentid", meta.getEventid());
 
        List<?> list = basicMapper.selectList(wrapper);
        if (null == list || list.size() == 0) {
            return null;
        }
        if (!(list.get(0) instanceof BaseEntity)) {
            return null;
        }
 
        return list;
    }
 
    /**
     * 获取附件字段
     */
    public static Field getAnnexField(Object obj, String tab) {
        try {
            String str = ATTACH_TABS.get(tab);
 
            Field field = obj.getClass().getDeclaredField(str);
            field.setAccessible(true);
 
            return field;
        } catch (Exception ex) {
            return null;
        }
    }
 
    /**
     * 获取附件名称
     */
    public static String getAnnexName(Object obj, Field field) {
        try {
            Object val = field.get(obj);
 
            return null == val ? null : val.toString().trim();
        } catch (Exception ex) {
            return null;
        }
    }
 
    /**
     * 查找附件文件
     */
    private String findAnnexFile(String name, String folder, List<String> files) {
        name = File.separator + name.split("\\.")[0].trim().toLowerCase();
        for (String file : files) {
            if (file.toLowerCase().contains(folder) && file.toLowerCase().contains(name)) {
                return file;
            }
        }
        for (String file : files) {
            if (file.toLowerCase().contains(name)) {
                return file;
            }
        }
 
        return null;
    }
 
    /**
     * 插入Excel附件
     */
    private int insertXlsAnnex(UserEntity ue, MetaEntity meta, BaseEntity be, String file) {
        File f = new File(file);
        if (!f.exists() || f.isDirectory()) {
            return 0;
        }
 
        String md5 = FileHelper.getFileMd5(file);
        AttachEntity old = attachService.selectByTabAndGuid(meta.getTab(), be.getEventid(), md5);
        if (null != old) {
            return 0;
        }
 
        String fileName = FileHelper.getFileName(file);
        double sizes = FileHelper.sizeToMb(f.length());
 
        AttachEntity ae = getAttachEntity(ue, meta.getTab(), be.getEventid(), fileName, md5, sizes);
        String targetPath = pathHelper.getConfig().getUploadPath() + File.separator + ae.getPath();
 
        try {
            FileUtils.copyFile(f, new File(targetPath));
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
 
        return attachService.insert(ae);
    }
 
    /**
     * 获取附件实体类
     */
    protected AttachEntity getAttachEntity(UserEntity ue, String tabName, String eventid, String fileName, String md5, double sizes) {
        AttachEntity entity = new AttachEntity();
        entity.setTab(tabName);
        entity.setTabGuid(eventid);
        entity.setName(fileName);
        entity.setGuid(md5);
        String subPath = PathHelper.getUploadPath() + File.separator + md5 + FileHelper.getExtension(fileName);
        entity.setPath(subPath);
        entity.setSizes(sizes);
        if (ue != null) {
            entity.setCreateUser(ue.getId());
        }
 
        return entity;
    }
 
    /**
     * 请求下载
     */
    public String downloadReqForGuids(UserEntity ue, List<String> guids) {
        List<AttachEntity> list = attachService.selectByGuids(guids);
 
        return downloadReq(ue, list);
    }
 
    /**
     * 请求下载
     */
    public String downloadReqForTabGuids(UserEntity ue, String tab, List<String> guids) {
        List<AttachEntity> list = attachService.selectByTabGuids(tab, guids);
 
        return downloadReq(ue, list);
    }
 
    /**
     * 请求下载
     */
    protected String downloadReq(UserEntity ue, List<AttachEntity> list) {
        if (null == list || list.isEmpty()) {
            return null;
        }
 
        String zipName = StringHelper.YMDHMS2_FORMAT.format(new Date()) + ".zip";
        String zipFile = pathHelper.getDownloadFullPath() + File.separator + zipName;
 
        ZipFile zip = Zip4jHelper.createZipFile(zipFile, null);
        ZipParameters params = Zip4jHelper.getZipParams(false);
        addZipFiles(zip, params, list);
 
        DownloadEntity downloadEntity = getDownloadEntity(ue, zipFile, null);
        int rows = downloadMapper.insert(downloadEntity);
 
        return rows > 0 ? downloadEntity.getGuid() : null;
    }
 
    /**
     * 添加Zip文件
     */
    private void addZipFiles(ZipFile zip, ZipParameters params, List<AttachEntity> list) {
        int i = 1;
        String uploadPath = pathHelper.getConfig().getUploadPath();
        for (AttachEntity ae : list) {
            try {
                String filePath = uploadPath + File.separator + ae.getPath();
 
                File file = new File(filePath);
                if (!file.exists() || file.isDirectory()) {
                    continue;
                }
 
                zip.addFile(file, params);
                FileHeader header = zip.getFileHeader(file.getName());
                if (null != header) {
                    zip.renameFile(header, i + "_" + ae.getName());
                }
            } catch (Exception ex) {
                log.error(ex.getMessage(), ex);
            }
        }
    }
 
    /**
     * 获取下载实体类
     */
    private DownloadEntity getDownloadEntity(UserEntity ue, String file, String pwd) {
        DownloadEntity de = new DownloadEntity();
        de.setName(FileHelper.getFileName(file));
        // 1-Shp文件,2-专题图,3-元数据,4-业务数据,5-管道分析,6-统计报告,7-附件文件,8-瓦片文件
        de.setType(7);
        de.setSizes(FileHelper.sizeToMb(new File(file).length()));
        de.setDepid(ue.getDepid());
        de.setDcount(0);
        de.setPwd(pwd);
        de.setUrl(FileHelper.getRelativePath(file));
        de.setDescr("附件文件");
        de.setGuid(FileHelper.getFileMd5(file));
        de.setCreateUser(ue.getId());
        // de.setGeom(null)
 
        return de;
    }
}