Spring MVC上传文件和下载文件
上传文件
1首先在jsp页面中创建一个form表单
<form method="post" action="/hello.form" enctype="multipart/form-data">
<input type="file" name="file">
<input type="file" name="file">
<button>提交</button>
<a href="down.form?fileName=3.jpg">手机图片</a>
</form>
2在springmvc.xml中注入配置
<bean id="CommonsMultipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--编码格式-->
<property name="defaultEncoding" value="UTF-8"></property>
<!--上传文件大小-->
<property name="maxUploadSize" value="10000000"></property>
</bean>
3在控制层方面
@RequestMapping("/hello.form")
public String upload(MultipartFile file[],HttpServletRequest request) throws IOException {
//循环上传路径
for (int i = 0; i < file.length; i++) {
String realPath = request.getServletContext().getRealPath("/down/");
//获取上传的文件名
String name = file[i].getOriginalFilename();
//更改名字 为了防止名字重复而覆盖
String name1= new Random().nextInt(100)+name;
File file1 = new File(realPath + name1);
//transferTo()方法是springmvc封装的方法,用于图片上传时,把内存中图片写入磁盘
file[i].transferTo(file1);
}
return "success";
}
4打开jsp页面选取文件
上传成功
下载文件中有些文件可以直接用超链接进行下载,但有些文件就不能,因此为了一劳永逸,我们统一进行转换格式
@RequestMapping("/down.form")
public ResponseEntity<byte[]> load(@RequestParam("fileName") String fileName,HttpServletRequest request) throws IOException {
//首先获取下载的路径
String realPath = request.getServletContext().getRealPath("/down/");
File file = new File(realPath + fileName);
//转换格式 某些进制的格式无法进行下载
String name = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
//转流 获取Http的所有头部
HttpHeaders hh = new HttpHeaders();
hh.setContentDispositionFormData("attachment",name);
hh.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),hh, HttpStatus.CREATED);
}
之后我们就可以成功的下载文件了