前言
今天学习使用springboot实现文件上传与下载功能,在实现文件上传的时候代码都没问题,但是每次提交后端都包空指针异常,最后发现获取的file为null。
先看代码
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<div style="text-align: center">
<form action="/uploadFile" method="post" enctype="multipart/form-data">
上传:<input type="file" name="filename"/>
<input type="submit" value="submit"/>
</form>
</div>
</body>
</html>
控制器代码
package com.hjk.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@Controller
public class FileController {
@GetMapping("/toUpload")
public String toUpload(){
return "upload";
}
@RequestMapping(value = "/uploadFile",method = RequestMethod.POST)
public String uploadFile(MultipartFile file){
String filename = file.getOriginalFilename();
String dirPath = "D:/file/";
File filePath = new File(dirPath);
if (!filePath.exists()){
filePath.mkdir();
}
try {
file.transferTo(new File(dirPath+filename));
} catch (IOException e) {
e.printStackTrace();
}
return "upload";
}
}
解决方式
我也看了很多博客,有的说是没有注册multipartResolver这个Bean,有的说是版本问题等等,还有的说是前端没有设置enctype类型。按照他们的方式我都进行了修改,但是我这个问题还是没有解决。
最终实现: 最后我在控制器方法里面参数加上了@RequestParam注解,这个后端就能获取文件了。
-
@RequestPara(“filename”)必须获取参数名为filename的file参数
-
@RequestParam()默认为必传属性,可以通过@RequestParam(required = false)设置为非必传。因为required值默认是true,所以默认必传
-
@RequestParam(“filename”)或者@RequestParam(value = “filename”)指定参数名
-
@RequestParam(defaultValue = “0”)指定参数默认值
最后代码
package com.hjk.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@Controller
public class FileController {
@GetMapping("/toUpload")
public String toUpload(){
return "upload";
}
@RequestMapping(value = "/uploadFile",method = RequestMethod.POST)
public String uploadFile(@RequestParam("filename") MultipartFile file){
String filename = file.getOriginalFilename();
String dirPath = "D:/file/";
File filePath = new File(dirPath);
if (!filePath.exists()){
filePath.mkdir();
}
try {
file.transferTo(new File(dirPath+filename));
} catch (IOException e) {
e.printStackTrace();
}
return "upload";
}
}
我的这个springboot版本是2.6.6至于真正原因现在不想思考了,等以后遇到再改吧。不知道这个对你有没有帮助。