在eclipse中的javaEE环境下:导入必要的架包
web.xml的配置文件:
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://monsMultipartResolver"> <!-- 默认的字符编码 --> <property name="defaultEncoding" value="UTF-8"></property> <!-- 上传文件的大小 ,最大上传大小--> <property name="maxUploadSize" value="1024000"></property> </bean> </beans>
handler类方法:实现文件的上传和下载的方法
@Controllerpublic class SpringMVCTest { @Autowired private EmployeeDao employeeDao; //实现文件的下载 //需要说明的是文件的上传和下载不需要其他配置 @RequestMapping("testResponseEntity") public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException{ byte[] body=null; ServletContext servletContext=session.getServletContext(); ///files/abc.txt:所要下载文件的地址 InputStream in=servletContext.getResourceAsStream("/files/abc.txt"); body=new byte[in.available()]; in.read(body); HttpHeaders headers=new HttpHeaders(); //响应头的名字和响应头的值 headers.add("Content-Disposition", "attachment;filename=abc.txt"); HttpStatus statusCode=HttpStatus.OK; ResponseEntity<byte[]> response=new ResponseEntity<byte[]>(body, headers, statusCode); return response; } //文件上传, @RequestMapping("/testFileUpload") public String testFileUpload(@RequestParam("desc") String desc, @RequestParam("file") MultipartFile file) throws IOException{ System.out.println("desc:"+desc); System.out.println("OriginalFilename"+file.getOriginalFilename()); System.out.println("InputStream"+file.getInputStream()); return "success"; } }
jsp页面:index.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>Insert title here</title></head><body> <center> <!-- 文件上传的表单 --> <form action="testFileUpload" method="post" enctype="multipart/form-data"> File:<input type="file" name="file"/> Desc:<input type="text" name="desc"/> <input type="submit" value="Submit"/> </form> <br><br> <!-- 文件的下载 --> <a href="testResponseEntity" rel="external nofollow" >Test ResponseEntity</a> </center> </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>Insert title here</title></head><body> <h3>Success page</h3> </body></html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。