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, "文件上传失败");
|
}
|
}
|
|
}
|