springboot项目在还没打包时,很多人喜欢把图片上传后,保存在项目的静态资源下,就像下面的图片那样
但是,我们不应该把与项目无关的资源全放在这,最好是无论在本地运行还是部署到服务器,都能做到“干湿分离”
so:
我们可以在他打包后的同级目录下设置upload文件夹
那用代码如何实现?
第一种(不推荐),还是不够灵活
配置application.properties文件, 在配置文件中声明图片的绝对路径及相对路径
server.port=8899
file.upload.path=F://images/
file.upload.path.relative=/images/**
第二种:
详细借鉴:
https://blog.csdn.net/qq_40298902/article/details/106609090
后端对应控制器的代码
```handlebars
//来到单文件上传页面(非异步)
@GetMapping("/toSingleUpload")
public String singleUpload() throws FileNotFoundException {
return "singleUpload";
}
//上传图片(非异步)
@PostMapping("/singleUploadFile")
public String singleUploadFile(MultipartFile file, Model model){
String fileName=file.getOriginalFilename(); //获取文件名以及后缀名
//fileName= UUID.randomUUID()+"_"+fileName;//重新生成文件名(根据具体情况生成对应文件名)
//获取jar包所在目录
ApplicationHome h = new ApplicationHome(getClass());
File jarF = h.getSource();
//在jar包所在目录下生成一个upload文件夹用来存储上传的图片
String dirPath = jarF.getParentFile().toString()+"/upload/";
System.out.println(dirPath);
File filePath=new File(dirPath);
if(!filePath.exists()){
filePath.mkdirs();
}
try{
//将文件写入磁盘
file.transferTo(new File(dirPath+fileName));
//上传成功返回状态信息
model.addAttribute("uploadStatus","上传成功");
}catch (Exception e){
e.printStackTrace();
//上传失败,返回失败信息
model.addAttribute("uploadStatus","上传失败:"+e.getMessage());
}
//携带上传状态信息回调到文件上传页面
return "singleUpload";
}
我再说一下如何访问已经上传的项目:
建类
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {
/**
* 为上传照片做准备,项目死图放在了static下,但是用户上传的其他照片等应该有他自己的位置
* 这里将打包后war包的同级目录上建一个upload文件夹,用于存储用户的上传文件
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 获取war包所在目录
ApplicationHome home=new ApplicationHome(getClass());
File warSource = home.getSource();
// 在war包所在目录下生成一个upload文件夹用来存上传的文件
String dirPath = warSource.getParentFile().toString()+"/upload/";
registry.addResourceHandler("/upload/**").addResourceLocations("file:/"+dirPath);
}
}