一、SpringMVC的配置文件
在其中加上
id属性一定要写上,且只能为multipartResolver
<!-- 文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf8"></property>
<property name="maxUploadSize" value="71680"></property>
</bean>
二、jsp
enctype属性记得一定要改,method的方式为post
<form action="${pageContext.request.contextPath}/testUp" method="post" enctype="multipart/form-data"> 文件:<input type="file" name="photo"><br> des:<input type="text" name="des"><br> <input type="submit"><br> </form>
三、写controller层
@Controller public class Upfile { @RequestMapping("/testUp") public void testUp(
@RequestParam(value = "photo") CommonsMultipartFile file, @RequestParam(value = "des") String des,
HttpServletRequest request
) throws IOException { System.out.println(des); // 获取web ServletContext context = request.getServletContext(); // 获取路径的真实路径 String realPath = context.getRealPath("/upload"); // 路径如果不存在就创建路径,这里只是文件夹 File file1 = new File(realPath); if (!file1.exists()) { file1.mkdirs(); } // 获取文件名 String fileName = file.getOriginalFilename(); // 获取输入流 InputStream in = file.getInputStream(); // 获取一个UUID作为前缀 String prefix = UUID.randomUUID().toString().replace("-", ""); // 获取输出流 文件为 路径+前缀+文件名 OutputStream out = new FileOutputStream(new File(realPath + "\" + prefix + fileName)); IOUtils.copy(in, out); out.close(); in.close(); } }