在SpringMVC中,想要实现上传和下载比较简单
上传
上传下载第一步,前加入jar包
commons-fileupload-1.2.1.jarcommons-io-2.0.jar
加入jar包之后,可以在Spring的配置文件中配置上传文件的一些限制
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property> // 编码
<property name="maxUploadSize" value="#{1024*1024*20}"></property> // 上传文件最大为多少
</bean>
上传页面
<body>
<form method="post" action="/UpLoad" enctype="multipart/form-data">
userName:<input type="text" name="userName"><br>
file:<input type="file" name="file" ><br>
<input type="submit" value="提交">
</form>
</body>
Controller层
@RequestMapping("/UpLoad")
public String upload(@RequestParam(value = "userName", required = false) String userName,
@RequestParam("file")MultipartFile file, Model model) throws IOException {
System.out.println(file.getOriginalFilename()); // 文件名
System.out.println(file.getName()); // file表单对应的name属性值
System.out.println(file.getSize()); // 文件大小
file.transferTo(new File("I:\\upload\\" + file.getOriginalFilename()));
return "success";
}
实验演示
浏览器页面
控制台输出
至此,上传就完成了。
下载
controller层
@RequestMapping("/download")
public ResponseEntity<byte[]> download(HttpSession session) throws IOException {
ServletContext servletContext = session.getServletContext();
FileInputStream fileInputStream = new FileInputStream(new File("I:\\copy.txt"));
byte[] bytes = new byte[fileInputStream.available()];
fileInputStream.read(bytes);
MultiValueMap<String, String> headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment;filename=copy.txt");
HttpStatus status = HttpStatus.OK;
return new ResponseEntity<byte[]>(bytes, headers, status);
}
jsp页面层
<body>
<a href="/download">下载</a>
</body>
演示效果
到这就完成了下载。