spring mvc 上传文件和表单时报400错误

bug复现

代码

这是html的代码,用的是所有的设置看起来都是正确的。

<form action="http://localhost:8081/student/both" method="POST" enctype="multipart/form-data">
	stuId: <input type="text" name="stuId"/><br/>
	detailId: <input type="text" name="detailId"/><br/>
	remarks: <input type="text" name="remarks"/><br/>
	picture: <input type="file" name="picture"/><br/>
	<input type="submit" value="提交"/>
</form>

这是控制层的代码

    @RequestMapping(value = "/both", method = RequestMethod.POST, produces="text/html;charset=UTF-8")
    @ResponseBody
    public String both(MultipartFile picture, ApplyScore applyScore) {
        return applyScore.getStuId() + ", " + picture.getOriginalFilename();
    }

显示情况

打开浏览器进入html页面中后是这样子的

点击提交后报400错误,也就是下图

问题原因

经过多方资料查证,发现问题出在了文件的变量名上,file的name不可以是picture,我将所有的picture改成了myfile之后再次提交就成功了。

以下是修改过之后的代码。

<form action="http://localhost:8081/student/both" method="POST" enctype="multipart/form-data">
	stuId: <input type="text" name="stuId"/><br/>
	detailId: <input type="text" name="detailId"/><br/>
	remarks: <input type="text" name="remarks"/><br/>
	picture: <input type="file" name="myfile"/><br/>
	<input type="submit" value="提交"/>
</form>
    @RequestMapping(value = "/both", method = RequestMethod.POST, produces="text/html;charset=UTF-8")
    @ResponseBody
    public String both(MultipartFile myfile, ApplyScore applyScore) {
        return applyScore.getStuId() + ", " + myfile.getOriginalFilename();
    }

以下是正确的程序运行截图

总结

变量名尽量取的不容易和程序的一些关键词重复,否则容易出现错误。

猜你喜欢

转载自blog.csdn.net/allenChenZhiMing/article/details/81539277