SpringMVC 上传文件(文件非必填)MultipartHttpServletRequest
原文:https://blog.csdn.net/dorothy1224/article/details/79136676
上传文件(文件非必填)MultipartHttpServletRequest
背景:
在表单提交时,有上传文件内容,但此内容非必填项。
在无上传文件入参时,接收类型仍写MultipartHttpServletRequest时,直接报错:
Current request is not of type [org.springframework.web.multipart.MultipartHttpServletRequest]: org.apache.catalina.connector.RequestFacade@3d1e5bd1
- 1
解决:
public void saveSystemParaMul(HttpServletRequest httpRequest,
HttpServletResponse response) {
if (httpRequest instanceof MultipartHttpServletRequest) {
MultipartHttpServletRequest request = (MultipartHttpServletRequest) httpRequest;
systemParameterService.saveSystemParaMul(request);
}else{
systemParameterService.saveSystemPara(httpRequest);
}
messager.jsonMessager().success().send(response);
}
主要思路:
1. 先判断httpRequest 是否含有文件类型
if (httpRequest instanceof MultipartHttpServletRequest)
2. 若含文件,则将httpRequest 转换为MultipartHttpServletRequest类型。
MultipartHttpServletRequest request = (MultipartHttpServletRequest) httpRequest;
知识储备:
当使用MultipartHttpServletRequest类型接收参数,spring处理请求的时候,首先第一步就去检查当前请求是否为上传文件的请求。所以,在文件为空时,就会报错,故将接收类型仍改为通用的HttpServletRequest 。
解决此问题参考的blog:
https://www.cnblogs.com/dongying/p/4388464.html
http://blog.csdn.net/chenchunlin526/article/details/70945877
版权声明:本文为博主原创文章,未经博主允许不得转载。
https://blog.csdn.net/Dorothy1224/article/details/79136676