fuliqi
2024-07-16 38f9471ecf47b7c15b352113bc0f5a2ec1e64e7b
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
package com.ycl.jxkg.controller.student;
 
 
import com.ycl.jxkg.base.BaseApiController;
import com.ycl.jxkg.base.Result;
import com.ycl.jxkg.config.RuoYiConfig;
import com.ycl.jxkg.service.FileUpload;
import com.ycl.jxkg.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
 
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.UUID;
 
@RequiredArgsConstructor
@RequestMapping("/api/student/upload")
@RestController("StudentUploadController")
public class UploadController extends BaseApiController {
 
    private final UserService userService;
    private final RuoYiConfig ruoYiConfig;
 
    @PostMapping("/image")
    public Result questionUploadAndReadExcel(MultipartFile file) {
        // 检查文件是否为空
        if (file == null || file.isEmpty()) {
            return Result.fail(500, "上传的文件为空");
        }
        String randomName = null;
        HashMap hashMap = new HashMap(2);
        try {
            // 获取文件名
            String originalFileName = StringUtils.cleanPath(file.getOriginalFilename());
            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.put("name", originalFileName);
            hashMap.put("url", randomName);
        } catch (IOException e) {
            e.printStackTrace();
            // 返回失败响应
            return Result.fail(500, "文件上传失败");
        }
        userService.changePicture(getCurrentUser(), randomName);
        return Result.ok(hashMap);
    }
}