xiangpei
2024-05-15 fe29db7a08e9da70ca3c78db27a11e48fa5f6f43
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.controller.common;
 
import com.mindskip.xzs.base.RestResponse;
import com.mindskip.xzs.configuration.RuoYiConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
 
import java.io.File;
import java.io.IOException;
 
/**
 * @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 fileName = StringUtils.cleanPath(file.getOriginalFilename());
 
            // 指定文件存储路径
            String uploadDir = ruoYiConfig.getUrl(); // 修改为您希望存储的目录
            // 如果目录不存在,则创建目录
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // 构建目标文件的路径
            String filePath = uploadDir + "/" + fileName;
            // 将文件保存到目标位置
            file.transferTo(new File(filePath));
            // 返回成功响应
            return RestResponse.ok("文件上传成功");
        } catch (IOException e) {
            e.printStackTrace();
            // 返回失败响应
            return RestResponse.fail(500, "文件上传失败");
        }
    }
 
}