jinlin
2025-03-01 86f02fee03614fef275c6e0c355d73318ca3025e
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
package com.example.server.utils;
 
import org.springframework.core.io.ByteArrayResource;
import org.springframework.web.multipart.MultipartFile;
 
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.Paths;
 
public class FileUtils {
 
    public static MultipartFile convertFileToMultipartFile(String filePath) throws IOException {
        Path path = Paths.get(filePath);
        String fileName = path.getFileName().toString();
        byte[] fileContent = Files.readAllBytes(path);
        ByteArrayResource resource = new ByteArrayResource(fileContent);
 
        return new CustomMultipartFile(resource, fileName);
    }
 
    private static class CustomMultipartFile implements MultipartFile {
 
        private final ByteArrayResource resource;
        private final String fileName;
 
        public CustomMultipartFile(ByteArrayResource resource, String fileName) {
            this.resource = resource;
            this.fileName = fileName;
        }
 
        @Override
        public String getName() {
            return null;
        }
 
        @Override
        public String getOriginalFilename() {
            return fileName;
        }
 
        @Override
        public String getContentType() {
            return null;
        }
 
        @Override
        public boolean isEmpty() {
            return false;
        }
 
        @Override
        public long getSize() {
            return resource.contentLength();
        }
 
        @Override
        public byte[] getBytes() throws IOException {
            return resource.getByteArray();
        }
 
        @Override
        public InputStream getInputStream() throws IOException {
            return resource.getInputStream();
        }
 
        @Override
        public void transferTo(File dest) throws IOException, IllegalStateException {
            Files.copy(resource.getInputStream(), dest.toPath());
        }
    }
}