1.若依框架提供了FileUploadUtils
工具类,用于处理文件上传,轻松实现文件的本地上传。
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.file.FileUploadUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class FileUploadController {
@PostMapping("/upload")
public Result<?> handleFileUpload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return Result.error("文件为空");
}
try {
// 使用FileUploadUtils工具类保存文件
String filePath = FileUploadUtils.upload("C:\\uploads", file);
return Result.ok("文件上传成功,保存路径:" + filePath);
} catch (Exception e) {
e.printStackTrace();
return Result.error("文件上传失败: " + e.getMessage());
}
}
}
该方法接受文件保存的目录和上传的文件作为参数,并返回文件保存的路径。
通过使用FileUploadUtils
工具类,我们可以更加简洁地处理文件上传,并且可以利用其提供的一些便捷功能,如生成文件名、处理文件路径等。
2.获取文件名和文件路径
// 生成文件名
String fileName = FileUploadUtils.getName(file.getOriginalFilename());
// 处理文件路径
String filePath = FileUploadUtils.extractFilename(fileName, "C:\\uploads", file);