liujie
2026-05-21 0e5d431f85612bf3abc0515fb6e46e500b5cdfe1
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
package com.estate.expert.admin.service.impl;
 
import com.estate.expert.admin.domain.misc.UserFile;
import com.estate.expert.admin.domain.misc.UserFileDto;
import com.estate.expert.admin.domain.user.User;
import com.estate.expert.admin.enums.BizResultCode;
import com.estate.expert.admin.service.UserFileService;
import com.estate.expert.admin.service.common.CrudServiceBaseImpl;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
 
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.UUID;
 
/**
 * 用户文件服务实现
 */
@Service
@Log4j
public class UserFileServiceImpl extends CrudServiceBaseImpl<UserFile, UserFileDto> implements UserFileService {
 
    @Value("${file.upload.dir}/files")
    private String UPLOAD_DIR;
 
    private Path fileLocation;
 
    @PostConstruct
    void init(){
        fileLocation  = Path.of(UPLOAD_DIR).toAbsolutePath().normalize();
 
        try {
            Files.createDirectories(this.fileLocation);
        } catch (Exception ex) {
            throw new RuntimeException("Could not create the directory where the uploaded files will be stored.", ex);
        }
    }
 
 
    @Override
    public UserFileDto upload(User user, File file) {
        var multipartFile = new MultipartFile() {
            @Override
            public String getName() {
                return file.getName();
            }
 
            @Override
            public String getOriginalFilename() {
                return file.getName();
            }
 
            @Override
            public String getContentType() {
                if(file.getName().contains(".jpg"))
                    return "image/jpeg";
                if(file.getName().contains(".pdf"))
                    return "application/pdf";
                if(file.getName().contains(".docx"))
                    return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                if(file.getName().contains(".png"))
                    return "image/png";
                return "application/octet-stream";
            }
 
            @Override
            public boolean isEmpty() {
                return file.length() == 0;
            }
 
            @Override
            public long getSize() {
                return file.length();
            }
 
            @Override
            public byte[] getBytes() throws IOException {
                return Files.readAllBytes(file.toPath());
            }
 
            @Override
            public InputStream getInputStream() throws IOException {
                return Files.newInputStream(file.toPath());
            }
 
            @Override
            public void transferTo(File dest) throws IOException, IllegalStateException {
                Files.copy(file.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
            }
        };
        return upload(user, multipartFile);
    }
 
    @Override
    public UserFileDto upload(User user, MultipartFile file) {
        var userFile = new UserFile();
        userFile.setName(UUID.randomUUID().toString());
        userFile.setOriginFileName(file.getOriginalFilename());
        userFile.setContentType(file.getContentType());
        userFile.setSize(file.getSize());
 
        var filename = file.getOriginalFilename();
        BizResultCode.UPLOAD_FILE_CONTAINS_ILLEGAL_CHARACTERS.check(filename == null || filename.contains(".."));
 
        var extension = !filename.contains(".") ? ""
                : file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
        userFile.setExtension(extension);
 
        try {
            var targetLocation = fileLocation.resolve(userFile.getName() + "." + extension);
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
            userFile = add(null, userFile);
        } catch (IOException e) {
            BizResultCode.UPLOAD_FILE_FAILED.check(true, e.getMessage());
        }
        return toDto(userFile);
    }
 
    @SneakyThrows
    @Override
    public InputStreamResource resolveResource(UserFile userFile) {
        var filePath = fileLocation.resolve(userFile.getName() + "." + userFile.getExtension()).normalize();
        if(!Files.exists(filePath)){
            return null;
        }
        return new InputStreamResource(Files.newInputStream(filePath));
    }
 
}