使用表單在springMVC的後臺上傳檔案時遇到500錯誤:The current request is not a multipart request
阿新 • • 發佈:2018-12-21
一、我出現錯誤的原因
是在前端的表單屬性裡沒有加入這一屬性enctype="multipart/form-data",然後繼續執行Tomcat, 上傳還是報一樣的錯誤,繼續認真觀看,發現我使用表單的預設提交方式,所以把提交方式改為method="post", 再次執行Tomcat上傳檔案就沒有報錯了,還有要記springMVC的配置檔案上傳相關的也必不可少。如果你跟我的錯誤一樣的話, 希望我的解析能夠給你提供一點點的幫助。
二、正確的程式碼
1、後臺
@Controller @RequestMapping("user") public class UserAction { @RequestMapping("upload1") public String upload1( @RequestParam(value = "myfile", required = false) MultipartFile file, HttpServletRequest request, Model model) throws IllegalStateException, IOException { String path = request.getSession().getServletContext() .getRealPath("upload"); String fileName = file.getOriginalFilename();// "1.png" fileName = UUID.randomUUID().toString().replace("-", "") + fileName.substring(fileName.lastIndexOf("."));// XXXX.png File targetFile = new File(path, fileName);// "C:///.../upload/XXX.png" if (!targetFile.exists()) { targetFile.mkdirs(); } file.transferTo(targetFile); // 到這裡,檔案上傳已經結束! model.addAttribute("newfile", fileName);// XXX.png return "index";// index.jsp } }
2、前臺
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="user/upload1.do" method="post" enctype="multipart/form-data"> 單檔案上傳:<input type="file" name="myfile"> <input type="submit" value="上傳"> <hr> <img src="upload/${newfile}"/> </form> </body> </html>
3.配置
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="user/upload1.do" method="post" enctype="multipart/form-data"> 單檔案上傳:<input type="file" name="myfile"> <input type="submit" value="上傳"> <hr> <img src="upload/${newfile}"/> </form> </body> </html>