zxl
昨天 f9acca94bd913c3e155dc86245df372910f8d76e
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
package com.mindskip.xzs.controller.common;
 
import com.mindskip.xzs.base.RestResponse;
import com.mindskip.xzs.configuration.RuoYiConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.UUID;
 
/**
 * @author:xp
 * @date:2024/5/15 17:02
 */
 
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/upload")
public class UploadController {
 
    private final RuoYiConfig ruoYiConfig;
 
    /**
     * 通用上传请求(单个)
     */
    @PostMapping("/upload")
    public RestResponse uploadFile(MultipartFile file) throws Exception
    {
//        // 检查文件是否为空
//        if (file.isEmpty()) {
//            return RestResponse.fail(500, "上传的文件为空");
//        }
        try {
            // 获取文件名
            String originalFileName = StringUtils.cleanPath(file.getOriginalFilename());
            String randomName = UUID.randomUUID().toString().replace("-", "") + originalFileName.substring(originalFileName.lastIndexOf("."));
            // 指定文件存储路径
            String uploadDir = ruoYiConfig.getUrl(); // 修改为您希望存储的目录
            // 如果目录不存在,则创建目录
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // 构建目标文件的路径
            String filePath = uploadDir + "/" + randomName;
            // 将文件保存到目标位置
            file.transferTo(new File(filePath));
            // 返回成功响应
            HashMap hashMap = new HashMap(2);
            hashMap.put("name", originalFileName);
            hashMap.put("url", randomName);
            return RestResponse.ok(hashMap);
        } catch (IOException e) {
            e.printStackTrace();
            // 返回失败响应
            return RestResponse.fail(500, "文件上传失败");
        }
    }
 
    /**
     * 下载文件(单个)
     */
    @GetMapping("/download")
    public void download(@RequestParam String url, @RequestParam String fileName, HttpServletResponse response) throws Exception
    {
        // 提取文件路径
        String filePath = ruoYiConfig.getUrl() + File.separator + url;
 
        File file = new File(filePath);
 
        // 检查文件是否存在
        if (!file.exists()) {
            throw new RuntimeException("文件不存在");
        }
 
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setContentLengthLong(file.length()); // 设置文件大小,便于浏览器显示进度
 
 
        // 流式传输:使用缓冲流分块读写,避免一次性加载整个文件到内存
        try (InputStream in = new BufferedInputStream(new FileInputStream(file));
             OutputStream out = new BufferedOutputStream(response.getOutputStream())) {
 
            byte[] buffer = new byte[8192]; // 8KB缓冲区
            int len;
            // 循环读取文件内容,每次读8KB,写入响应输出流
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush(); // 确保最后一部分数据被写出
        } catch (IOException e) {
            throw new RuntimeException("文件下载失败", e);
        }
 
 
//        // 读取文件内容
//        byte[] fileContent = Files.readAllBytes(file.toPath());
//
//        // 设置响应头
//        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
//        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
//
//
//
//        // 将文件内容写入响应输出流
//        response.getOutputStream().write(fileContent);
//        response.getOutputStream().flush();
    }
 
}