包
- <dependency>
- <groupId>commons-lang</groupId>
- <artifactId>commons-lang</artifactId>
- <version>2.6</version>
- </dependency>
- <dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- <version>2.4</version>
- </dependency>
- <dependency>
- <groupId>commons-fileupload</groupId>
- <artifactId>commons-fileupload</artifactId>
- <version>1.2.2</version>
- </dependency>
- <dependency>
- <groupId>org.hibernate.validator</groupId>
- <artifactId>hibernate-validator</artifactId>
- <version>6.1.5.Final</version>
- </dependency>
控制器
- /*
- value = "/myupload"是路由地址
- method = RequestMethod.POST 规定POST请求
- */
- @RequestMapping(value = "/myupload", method = RequestMethod.POST)
- public String myupload(MultipartFile photo, HttpSession session) {
- //获取浏览器上传的文件名称
- String filename = photo.getOriginalFilename();
- //获取文件后缀
- String suffix = filename.substring(filename.lastIndexOf("."));
- //重新瓶装文件名称
- filename = UUID.randomUUID().toString() + suffix;
- System.out.println(filename);
- //获取项目的存储路径, 并在上下文中创建photo的文件夹
- String path = session.getServletContext().getRealPath("photo");
- System.out.println(path);
- File file = new File(path);
- //不存在就创建路径
- if (!file.exists()) {
- file.mkdir();
- }
- //F:\apache-tomcat-8.5.75\webapps\ROOT\photo\0b4800c3-76ec-4d6d-a262-b52875b89033.txt
- filename = path + "/" + filename;
- File updatefile = new File(filename);
- try {
- //执行文件上传
- photo.transferTo(updatefile);
- } catch (IOException e) {
- e.printStackTrace();
- }
- return "index";
- }