一个文件上传引发的问题“Spring MultipartResolver 或者 ServletFileUpload”

今天在开接口时,将web 项目的“文件上传”代码移动到app项目时,发现上传的文件和参数获取不到:

代码是这样的:

DiskFileItemFactory factory = new DiskFileItemFactory(1024 * 1024 * 20, null);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
upload.setSizeMax(1024 * 1024 * 20);
List<FileItem> fileItems = upload.parseRequest(req);

后来在网上找了一下原因,“MultipartResolver 和ServletFileUpload 不能同时使用,否则会有冲突”

然后将代码修改成这样:

MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
Iterator<String> it = multiRequest.getFileNames();

配置文件:
<bean id="multipartResolver"             
       class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize" value="10000000" />
</bean>

因为提交方式为:multipart/form-data,然后又了解了下这几种类型

application/x-www-form-urlencoded:窗体数据被编码为名称/值对。这是标准的编码格式。 

  当action为get时候,浏览器用x-www-form-urlencoded的编码方式把form数据转换成一个字串(name1=value1&name2=value2...),然后把这个字串append到url后面,用?分割,加载这个新的url。

    当action为post时候,浏览器把form数据封装到http body中,然后发送到server。如果没有type=file的控件,用默认的application/x-www-form-urlencoded就可以了。

multipart/form-data:窗体数据被编码为一条消息,页上的每个控件对应消息中的一个部分。 

浏览器会把整个表单以控件为单位分割,并为每个部分加上Content-Disposition(form-data或者file),Content-Type(默认为text/plain),name(控件name)等信息,并加上分割符(boundary)。

text/plain:窗体数据以纯文本形式进行编码,其中不含任何控件或格式字符。

猜你喜欢

转载自blog.csdn.net/gu_zhang_w/article/details/82392024