🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## 说明 SpringMVC框架提供了MultipartFile对象,该对象表示上传的文件,要求变量名称必须和表单file标签的name属性名称相同. ## 原理 ![](https://box.kancloud.cn/09453e311ffe51589b8075b063139945_1304x608.png) ## 页面 ~~~ <form action="/spring/upload" method="post" enctype="multipart/form-data"> <input type="file" name="upload"> <input type="submit"> </form> ~~~ ## 配置文件解析器 ~~~ <!--配置文件解析器.id必须设置为multipartResolver--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--设置最大上传文件大小--> <property name="maxUploadSize" value="104857600"/> </bean> ~~~ ## 代码 ~~~ @RequestMapping(path = "/upload") public String testResponse(HttpServletRequest request, MultipartFile upload) throws Exception //MultipartFile变量名必须和表单的name一致 { String path = request.getSession().getServletContext().getRealPath("/uploads/"); File file = new File(path); if (!file.exists()) { file.mkdirs(); } //获取文件名 String fileName = upload.getOriginalFilename(); System.out.println(fileName); String s = UUID.randomUUID().toString().replace("-", ""); fileName = s + fileName; System.out.println(fileName); //上传到指定文件夹 upload.transferTo(new File(path, fileName)); return "success"; } ~~~