luohairen
2024-11-14 247cb86585a1d1894596ed18a6c93efecb992946
src/main/java/com/ycl/jxkg/controller/admin/UploadController.java
@@ -12,7 +12,9 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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;
@@ -40,6 +42,8 @@
    private static final String IMAGE_UPLOAD_FILE = "upFile";
    private final UserService userService;
    private final RuoYiConfig ruoYiConfig;
    @Autowired
    public UploadController(FileUpload fileUpload, SystemConfig systemConfig, UserService userService, RuoYiConfig ruoYiConfig) {
@@ -126,5 +130,37 @@
        }
    }
    @PostMapping("/img")
    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);
    }
}