标签:
一.文件下载
// 文件下载 @RequestMapping("/testResponseEntity") public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException{ byte[] body = null; InputStream in = session.getServletContext().getResourceAsStream("/file/abc.txt"); System.out.println("inputstream" + in); body = new byte[in.available()]; in.read(body); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment;filename=abc.txt"); ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, HttpStatus.OK); return response; }
二.文件上传
springmvc为文件上传提供了直接的支持,这种支持是通过即插即用的MultipartResolver实现的。
spring用jakarta commons FileUpload技术实现了MultipartResolver实现类:CommonsMultipartResolver
下面看如何来实现
1.引进如下jar包
commons-fileupload.jar
commons-io.jar (<-上面的jar的依赖包)
2.springmvc的配置文件中,配置如下
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"></property> </bean>
3.前台代码如下:
<form action="testFileUpload" enctype="multipart/form-data" method="POST"> File : <input type="file" name="file"><br> Desc : <input type="text" name="desc"><br> <input type="submit" value="Submit"> </form>
4.后台代码如下:
// 文件上传 @RequestMapping(value="/testFileUpload") public String testFileUpload(@RequestParam("desc") String desc, @RequestParam("file") MultipartFile file) throws IOException{ System.out.println("desc: "+ desc); System.out.println("file name: " + file.getOriginalFilename()); System.out.println("file inputstream" + file.getInputStream()); return "success"; }
标签:
原文地址:http://www.cnblogs.com/mianteno/p/5178788.html