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
package com.webmanage.controller;
 
import com.webmanage.common.Result;
import com.webmanage.service.MinioService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
 
/**
 * 文件上传下载控制器
 * 
 * @author webmanage
 * @date 2024-08-07
 */
@Slf4j
@RestController
@RequestMapping("/file")
@Api(tags = "文件管理")
public class FileController {
 
    @Autowired
    private MinioService minioService;
 
    /**
     * 上传文件
     */
    @PostMapping("/upload")
    @ApiOperation("上传文件")
    public Result<String> uploadFile(
            @ApiParam("文件") @RequestParam("file") MultipartFile file,
            @ApiParam("文件夹") @RequestParam(defaultValue = "common") String folder) {
        try {
            if (file.isEmpty()) {
                return Result.error("文件不能为空");
            }
            
            // 检查文件大小(限制为100MB)
            if (file.getSize() > 500 * 1024 * 1024) {
                return Result.error("文件大小不能超过500MB");
            }
            
            String fileName = minioService.uploadFile(file, folder);
            return Result.success("文件上传成功", fileName);
        } catch (Exception e) {
            log.error("文件上传失败: ", e);
            return Result.error("文件上传失败: " + e.getMessage());
        }
    }
 
    /**
     * 下载文件(路径参数方式)
     */
    @GetMapping("/download/{fileName}")
    @ApiOperation("下载文件(路径参数)")
    public ResponseEntity<InputStreamResource> downloadFileByPath(
            @ApiParam("文件名") @PathVariable String fileName,
            @ApiParam("原始文件名") @RequestParam(required = false) String originalName) {
        try {
            InputStream inputStream = minioService.downloadFile(fileName);
            
            // 如果没有提供原始文件名,从路径中提取
            if (originalName == null || originalName.isEmpty()) {
                String[] parts = fileName.split("/");
                originalName = parts[parts.length - 1];
            }
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", 
                    URLEncoder.encode(originalName, StandardCharsets.UTF_8.toString()));
            
            InputStreamResource resource = new InputStreamResource(inputStream);
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);
        } catch (Exception e) {
            log.error("文件下载失败: ", e);
            return ResponseEntity.notFound().build();
        }
    }
 
    /**
     * 下载文件(查询参数方式)
     */
    @GetMapping("/download")
    @ApiOperation("下载文件(查询参数)")
    public ResponseEntity<InputStreamResource> downloadFile(
            @ApiParam("文件名") @RequestParam String fileName,
            @ApiParam("原始文件名") @RequestParam(required = false) String originalName) {
        try {
            InputStream inputStream = minioService.downloadFile(fileName);
            
            // 如果没有提供原始文件名,从路径中提取
            if (originalName == null || originalName.isEmpty()) {
                String[] parts = fileName.split("/");
                originalName = parts[parts.length - 1];
            }
            
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", 
                    URLEncoder.encode(originalName, StandardCharsets.UTF_8.toString()));
            
            InputStreamResource resource = new InputStreamResource(inputStream);
            
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);
        } catch (Exception e) {
            log.error("文件下载失败: ", e);
            return ResponseEntity.notFound().build();
        }
    }
 
    /**
     * 获取文件预览URL(路径参数方式)
     */
    @GetMapping("/preview/{fileName}")
    @ApiOperation("获取文件预览URL(路径参数)")
    public Result<String> getPreviewUrlByPath(@ApiParam("文件名") @PathVariable String fileName) {
        try {
            String previewUrl = minioService.getPreviewUrl(fileName);
            return Result.success("获取预览URL成功", previewUrl);
        } catch (Exception e) {
            log.error("获取预览URL失败: ", e);
            return Result.error("获取预览URL失败: " + e.getMessage());
        }
    }
 
    /**
     * 获取文件预览URL(查询参数方式)
     */
    @GetMapping("/preview")
    @ApiOperation("获取文件预览URL(查询参数)")
    public Result<String> getPreviewUrl(@ApiParam("文件名") @RequestParam String fileName) {
        try {
            String previewUrl = minioService.getPreviewUrl(fileName);
            return Result.success("获取预览URL成功", previewUrl);
        } catch (Exception e) {
            log.error("获取预览URL失败: ", e);
            return Result.error("获取预览URL失败: " + e.getMessage());
        }
    }
 
    /**
     * 获取文件下载URL
     */
    @GetMapping("/download-url/{fileName}")
    @ApiOperation("获取文件下载URL")
    public Result<String> getDownloadUrl(@ApiParam("文件名") @PathVariable String fileName) {
        try {
            String downloadUrl = minioService.getDownloadUrl(fileName);
            return Result.success("获取下载URL成功", downloadUrl);
        } catch (Exception e) {
            log.error("获取下载URL失败: ", e);
            return Result.error("获取下载URL失败: " + e.getMessage());
        }
    }
 
    /**
     * 删除文件(路径参数方式)
     */
    @DeleteMapping("/delete/{fileName}")
    @ApiOperation("删除文件(路径参数)")
    public Result<Boolean> deleteFileByPath(@ApiParam("文件名") @PathVariable String fileName) {
        try {
            minioService.deleteFile(fileName);
            return Result.success("文件删除成功", true);
        } catch (Exception e) {
            log.error("文件删除失败: ", e);
            return Result.error("文件删除失败: " + e.getMessage());
        }
    }
 
    /**
     * 删除文件(查询参数方式)
     */
    @DeleteMapping("/delete")
    @ApiOperation("删除文件(查询参数)")
    public Result<Boolean> deleteFile(@ApiParam("文件名") @RequestParam String fileName) {
        try {
            minioService.deleteFile(fileName);
            return Result.success("文件删除成功", true);
        } catch (Exception e) {
            log.error("文件删除失败: ", e);
            return Result.error("文件删除失败: " + e.getMessage());
        }
    }
 
    /**
     * 检查文件是否存在
     */
    @GetMapping("/exists/{fileName}")
    @ApiOperation("检查文件是否存在")
    public Result<Boolean> fileExists(@ApiParam("文件名") @PathVariable String fileName) {
        try {
            boolean exists = minioService.fileExists(fileName);
            return Result.success("检查完成", exists);
        } catch (Exception e) {
            log.error("检查文件是否存在失败: ", e);
            return Result.error("检查文件是否存在失败: " + e.getMessage());
        }
    }
}