<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>单文件上传</title> </head> <body> <form action="/file/singleFile" method="post" enctype="multipart/form-data"> 用户名:<input type="text" name="username" /><br/> 文件上传:<input type="file" name="file"/><br/> <input type="submit" value="上传"/> </form> </body> </html>
@RequestMapping("/single") public String showSingleFile(){ return "singlefile"; }
@Controller @RequestMapping("/file") public class FileUploadController { @RequestMapping(value = "/singleFile",method = RequestMethod.POST) public String singleFile(MultipartFile file, String username, HttpServletRequest request){ String fileName = UUID.randomUUID().toString()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); String realPath = request.getServletContext().getRealPath("/fileupload"); System.out.println(realPath); File temp = new File(realPath,fileName); System.out.println(temp); try { file.transferTo(temp); } catch (IOException e) { e.printStackTrace(); } return "redirect:/page/ok"; } }
问题1:在浏览器地址栏输入http://localhost:8888/page/single,可以正常跳转到文件上传页面,但是IDEA控制台会有警告信息:
警告 [http-nio-8888-exec-6] org.springframework.web.servlet.PageNotFound.noHandlerFound No mapping for GET /favicon.ico
问题2:在文件上传页面点击跳转后,可以跳转至ok页面,但会文件并没有上传成功。IDEA控制台报错,第54行代码:file.transferTo(temp);
java.io.FileNotFoundException: E:\fikeupload\out\artifacts\fikeupload_war_exploded\fileupload\c65fcb1b-f6fe-4e27-971a-b09199589d85.jpg (系统找不到指定的路径。)