springmvc文件上传
一、导入相关依赖(还需要配置好springmvc的环境)
<dependency>
<groupId>commons-fileuploadgroupId>
<artifactId>commons-fileuploadartifactId>
<version>1.4version>
dependency>
二、配置springmvc.xml
id是固定不变的 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="10485760">property> bean>
三、编写接收controller
利用srpingmvc封装的MultipartFile对象
@PostMapping(value = "/fileUpload") public void FileUpload(MultipartFile file) throws IOException { String fileName = file.getOriginalFilename(); System.out.println("文件名 "+fileName); String path = request.getServletContext().getRealPath(""); path = path + "upload/"+fileName; File filePath = new File(path); if (!filePath.exists()){ filePath.mkdir(); } System.out.println("保存路径 "+filePath);
//直接执行保存操作 file.transferTo(filePath); }