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();
    }

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

总结

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

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值