前言:
根据工程与学习的需要,最近接触了文件上传的相关知识,一开始由android端使用volley上传,遇到点问题,最后换成了OKhttp,服务器端采用spring MVC和flask,都成功了,将我的学习历程记录下来,为了更好的分享。
正文:
一、Spring MVC文件上传
在Intellij IDEA下开发,确实新的编辑器用起来方便许多,具体的安装我也是按照网上的教程来搭建环境的,搭建过程比较简单,以下是我搭建成功的教程:是个系列教程:
需要自己下载tomcat,我使用它系统的tomcat报错了,所以改为自己的tomcat,maven也需要自己配置,系统的也遇到了问题,搭建好后运行第一个web程序,测试完成。
下面开始文件上传的工作,首先需要在maven的pom.xml中引入要文件传输的包:
<!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency> <!-- https://mvnrepository.com/artifact/com.liferay/org.apache.commons.fileupload --> <dependency> <groupId>com.liferay</groupId> <artifactId>org.apache.commons.fileupload</artifactId> <version>1.2.2.LIFERAY-PATCHED-1</version> </dependency>
然后修改dispatcher里的加上支持文件的配置:
<!-- 支持上传文件 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
我的dispatcher完整代码如下:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--指明 controller 所在包,并扫描其中的注解--> <context:component-scan base-package="com.controller"/> <!-- 静态资源(js、image等)的访问 --> <mvc:default-servlet-handler/> <!-- 开启注解 --> <mvc:annotation-driven/> <!--ViewResolver 视图解析器--> <!--用于支持Servlet、JSP视图解析--> <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/pages/"/> <property name="suffix" value=".jsp"/> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/> </beans>