SpringMV使用MultipartFile上传文件出现空指针异常

学习SpringMV使用MultipartFile上传文件出现空指针异常三大原因

原因1:未配置SpringMVC配置文件

编写配置文件有两种方式
第一种默认偷懒式
这种方式一般情况来说是没有问题的,就是没有去配置属性

<!-- MultipartResvler解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>

如有需要可以添加上属性配置
第一个属性是设置最大上传文件大小

<!-- MultipartResvler解析器 -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize" value="100000000"></property>
		<property name="defaultEncoding" value="utf-8"></property>
		<property name="fileItemFactory.sizeThreshold" value="0"></property>
	</bean>

原因2 : 请求参数不匹配

姓名:<input type="text" name="name"/><br/>
文件:<input type="file" name="imgfile"/><br/>
<input type="submit" value="提交">

表单中请求参数name必须和控制器中参数同名

@RequestMapping("upload")
	public String upload(MultipartFile imgfile,String name) throws IOException {
    
    
		MultipartResolver multipartResolver = null;
		System.out.println(name);
		System.out.println(imgfile);
		String fileName = imgfile.getOriginalFilename();//取文件名
		String suffix = fileName.substring(fileName.lastIndexOf("."));//取后缀名
		String uuid = UUID.randomUUID().toString();
		FileUtils.copyInputStreamToFile(imgfile.getInputStream(), new File("E:/"+uuid+suffix));
		return "/index.jsp";
	}

原因3 : 表单属性错误

这是一个最致命的问题,也是我在最开始遇到的问题,也是最无脑的问题,我看了其他关于这个空指针的问题,在原因12排除得不到解决的情况下就只会出现这个问题

<form action="upload" enctype="multipart/form-data" method="post">

表单中一定要设置enctype="multipart/form-data"这个属性,并且一定要注意form不能写成from,我就是因为这个一字之差困扰一天,虽然有人看到这个问题会觉得很弱智,但是我还是向强调下这个很容易错的,如有遇到MultipartFile上传文件出现空指针异常的问题,就按三个原因排查

虽然这篇博客技术性不高,但还是希望可以帮到别人,特别是新手

猜你喜欢

转载自blog.csdn.net/qq_45325916/article/details/104232460
今日推荐