1.文件上传
a.配置mySpring-servlet.xml
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 限制上传文件的大小 -1 为不限制 --> <property name="maxUploadSize" value="-1"> </property> </bean>
b.使用
@Controller public class uploadFile { @RequestMapping("/upload") public void upload(@RequestParam("myFile") CommonsMultipartFile file,HttpServletRequest req){ String fileName=file.getOriginalFilename(); String path=req.getSession().getServletContext().getRealPath("upload"); try { file.getFileItem().write(new File(path + File.separator + fileName)); } catch (Exception e) { e.printStackTrace(); } } }
c.解决中文乱码
①在表单中accept-charset="utf-8"
②web.xml文件中
<filter> <filter-name>Set Character Encoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>Set Character Encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>