文件上传
添加依赖
<!--文件上传--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>
配置文件上传解析器
<!--配置文件上传解析器--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="5242880" /> <property name="defaultEncoding" value="UTF-8" /> </bean>
测试
-
编写controller文章来源:https://www.toymoban.com/news/detail-783218.html
@Controller @RequestMapping("/account") public class AccountController { @RequestMapping(path="/upload") public String upload(HttpServletRequest request, MultipartFile upload,Model model) throws IOException { System.out.println("springmvc方式的文件上传"); //获取要上传的文件目录 String path = request.getSession().getServletContext().getRealPath("/uploads"); System.out.println("path:"+path); //根据文件上传的目录创建File对象,如果不存在则创建1个File对象 File file = new File(path); if(!file.exists()){ //创建一个file对象 file.mkdirs(); } //获取文件上传名称 String filename = upload.getOriginalFilename(); //完成文件上传 upload.transferTo(new File(path,filename)); model.addAttribute("msg", "欢迎你 springmvc"); return "success"; } }
-
在index.jsp里面定义超链接文章来源地址https://www.toymoban.com/news/detail-783218.html
<form action="/account/upload" method="post" enctype="multipart/form-data"> 文件: <input type="file" name="upload"></input> <input type="submit" value="提交"> </form>
到了这里,关于Spring MVC 文件上传的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!