在这段代码里面加一个本地如果没有这个文件夹的话就生成这个文件夹@Controller public class UploadController { @RequestMapping("/upload") public String toUpload(){ return "upload_tu"; } //文件上传 @PostMapping("/upload") public String upload(@RequestPart("headerImg") MultipartFile headerImg, @RequestPart("photos") MultipartFile[] photos, Model model) { try { if (!headerImg.isEmpty()) { String filename = headerImg.getOriginalFilename(); headerImg.transferTo(new File("E://file//" + filename)); } if(photos.length>0){ for(MultipartFile photo:photos){ if(!photo.isEmpty()){ String filename =photo.getOriginalFilename(); photo.transferTo(new File("E://file//" + filename)); } } } model.addAttribute("msg","上传成功!"); } catch (IOException e) { model.addAttribute("msg","上传失败"); } return "upload_tu"; } }
时间: 2024-02-14 16:17:29 浏览: 142
可以在方法体开始前添加以下代码来检查文件夹是否存在,如果不存在则创建它:
```
File file = new File("E://file//");
if (!file.exists()) {
file.mkdirs();
}
```
修改后的代码如下:
```
@Controller
public class UploadController {
@RequestMapping("/upload")
public String toUpload(){
return "upload_tu";
}
//文件上传
@PostMapping("/upload")
public String upload(@RequestPart("headerImg") MultipartFile headerImg,
@RequestPart("photos") MultipartFile[] photos,
Model model) {
try {
//检查文件夹是否存在,不存在则创建
File file = new File("E://file//");
if (!file.exists()) {
file.mkdirs();
}
if (!headerImg.isEmpty()) {
String filename = headerImg.getOriginalFilename();
headerImg.transferTo(new File("E://file//" + filename));
}
if (photos.length > 0) {
for (MultipartFile photo : photos) {
if (!photo.isEmpty()) {
String filename = photo.getOriginalFilename();
photo.transferTo(new File("E://file//" + filename));
}
}
}
model.addAttribute("msg","上传成功!");
} catch (IOException e) {
model.addAttribute("msg","上传失败");
}
return "upload_tu";
}
}
```
阅读全文