springmvc文件上传

来源:互联网 发布:淘宝客服名 编辑:程序博客网 时间:2024/06/05 19:53

1.jar commons-fileupload-1.2.2.jar

         commons-io-2.0.1.jar

2.xml文件中添加

  <!-- 支持上传文件 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

3.构建页面

uploadFile.jsp

  <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传</title>
</head>
<body>
<form action="<%=this.getServletContext().getContextPath() %>/test/uploadfile.html" method="post" enctype="multipart/form-data">
<input type="file" name="uploadFile" id="uploadFile" />
<input type="submit" value="上传"/>
</form>
</body>
</html>


success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传成功</title>
</head>
<body>
<h1>上传文件成功!</h1>
<img alt="" src="${fileUrl }" />
</body>
</html>


error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传失败</title>
</head>
<body>
<h1>上传文件失败!</h1>
</body>
</html>

4.controll类编写

@Controller@RequestMapping(value = "/test")public class UploadFileController {@RequestMapping("toUploadFile")public String toUpload(){return "test/uploadFile";}@RequestMapping("success")public String toSuccess(){return "test/success";}@RequestMapping("error")public String toError(){return "test/error";}@RequestMapping(value = "/uploadfile", method = RequestMethod.POST)public String uploadFile(@RequestParam(value = "uploadFile", required = true) MultipartFile file,HttpServletRequest request) {System.out.println("开始");String path = request.getServletContext().getRealPath("upload");String fileName = file.getOriginalFilename();System.out.println(path);File targetFile = new File(path, fileName);if (!targetFile.exists()) {targetFile.mkdirs();}// 保存try {file.transferTo(targetFile);request.getSession().setAttribute("fileUrl",request.getContextPath() + "/upload/" + fileName);return "redirect:success.html";} catch (Exception e) {e.printStackTrace();return "redirect:error.html";}}}


0 0