import com.lgy.util.Result;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
/**
* @Description TODO 文件Controller
* @Author admin
* @Date 2021/8/10
*/
@RestController
@RequestMapping("file")
public class FileController {
/**
* 文件保存路径,此处只是为演示,开发时一般使用 @value 注解注入或者写入常量类
*/
private final static String FILE_SAVE_PATH = "D:/file/picture/";
@RequestMapping("upload")
public Result upload(@RequestParam("file") MultipartFile file) {
//获取上传的文件名 比如:abc.jpg
String uploadFileName = file.getOriginalFilename();
//获取后缀 比如:.jpg
String suffixName = uploadFileName.substring(uploadFileName.lastIndexOf("."));
//此处生成 uuid 作为新的文件名称
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//此处拼接得到最终文件保存路径( D:/file/picture/生成的uuid.jpg)
String savePath = FILE_SAVE_PATH + uuid + suffixName;
File f = new File(savePath);
// f.getParentFile()获取文件的父级路径,即:FILE_SAVE_PATH 的值
if (!f.getParentFile().exists()) {
//mkdirs()是创建多级目录
f.getParentFile().mkdirs();
}
//保存文件
try {
file.transferTo(f);
} catch (IOException e) {
e.printStackTrace();
return new Result(1, "Upload failed!", e.getMessage());
}
return new Result(0, "Upload succeeded!");
}
}
SpringBoot文件上传并保存本地
最新推荐文章于 2025-03-20 19:12:59 发布
本文详细介绍了如何在SpringBoot应用中实现文件上传,并将文件保存到本地文件系统。内容包括配置文件处理,控制器方法设计,以及上传过程中的异常处理。
2077

被折叠的 条评论
为什么被折叠?



