xiangpei
2024-03-28 0f431b52e0936456bd165d9553761bfd8a5a0517
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
package com.mindskip.xzs.service.impl;
 
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.mindskip.xzs.configuration.property.SystemConfig;
import com.mindskip.xzs.service.FileUpload;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
 
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
 
@Service
@AllArgsConstructor
public class FileUploadImpl implements FileUpload {
    private final SystemConfig systemConfig;
    private final List<String> fileAllowExtension = Arrays.asList(".gif", ".GIF", ".jpg", ".JPG", ".jpeg", ".JPEG"
            , ".png", ".PNG", ".mp4", ".MP4", ".pdf", ".PDF", ".xlsx", ".XLSX", ".docx", ".DOCX");
 
 
    @Override
    public String fileUpload(File file, String fileName, String folder) {
        if (fileAllowExtension.stream().anyMatch(fe -> fileName.endsWith(fe))) {
            String filePath = String.format("%s/%s/%s", folder, UUID.randomUUID(), fileName);
            File destFile = new File(String.format("%s%s", systemConfig.getLocalStore().getResource(), filePath));
            File fileParent = destFile.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            FileUtil.copyFile(file, destFile);
            return systemConfig.getLocalStore().getUrl() + "/" + filePath;
        } else {
            return null;
        }
    }
 
    @Override
    public String fileUpload(InputStream inputStream, long fileSize, String fileName, String folder) {
        if (fileAllowExtension.stream().anyMatch(fe -> fileName.endsWith(fe))) {
            String filePath = String.format("%s/%s/%s", folder, UUID.randomUUID(), fileName);
            File destFile = new File(String.format("%s%s", systemConfig.getLocalStore().getResource(), filePath));
            File fileParent = destFile.getParentFile();
            if (!fileParent.exists()) {
                fileParent.mkdirs();
            }
            BufferedOutputStream out = FileUtil.getOutputStream(destFile.getPath());
            IoUtil.copy(inputStream, out, IoUtil.DEFAULT_BUFFER_SIZE);
            IoUtil.close(inputStream);
            IoUtil.close(out);
            return systemConfig.getLocalStore().getUrl() + "/" + filePath;
        } else {
            return null;
        }
    }
 
 
}