1、文件下载
- 代码示例
方式一: 图片名字由服务进行绑定
【index.jsp】
<body>
<a href="down">下载图片</a>
</body>
【TestUploadAndDownController.java】
@RequestMapping(value = "/down")
public ResponseEntity<byte[]> down(HttpSession session) throws Exception {
// 获取下载文件的路径
String realPath = session.getServletContext().getRealPath("img");
String finalPath = realPath + File.separator + "2.jpg";
InputStream is = new FileInputStream(finalPath);
// available():获取输入流所读取的文件的最大字节数
byte[] bt = new byte[is.available()];
is.read(bt);
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition","attachment;filename=zzz.jpg");
// 设置响应状态
HttpStatus status = HttpStatus.OK;
ResponseEntity<byte[]> entity = new ResponseEntity<>(bt, headers, status);
return entity;
}
测试:
方式二: 图片有请求方式来获取
【index.jsp】
<body>
<a href="down/1">下载图片</a>
</body>
【TestUploadAndDownController.java】
@RequestMapping(value = "/down/{username}")
public ResponseEntity<byte[]> down(@PathVariable("username") String username, HttpSession session) throws Exception {
// 获取下载文件的路径
String realPath = session.getServletContext().getRealPath("img");
String finalPath = realPath + File.separator + username+".jpg";
InputStream is = new FileInputStream(finalPath);
byte[] bt = new byte[is.available()];
is.read(bt);
// 获取请求头
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition","attachment;filename="+username+".jpg");
// 设置响应状态
HttpStatus status = HttpStatus.OK;
ResponseEntity<byte[]> entity = new ResponseEntity<>(bt, headers, status);
return entity;
}
测试:
2、文件上传
- 导入需要的Jar包
-
代码示例
【index.jsp】
<form action="up" method="post" enctype="multipart/form-data">
头像:<input type="file" name="uploadFile"/>
描述:<input type="text" name="desc"/>
<input type="submit" value="上传"/>
</form>
【配置spingmvc.xml】不配置上传则会报错
<!--
处理文件,将客户端上传的File文件,处理为MultipartFile
注意:文件解析器的bean中id必须设置为multipartResolver
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置文件解析的编码,注意:一定要和页面的pageEncoding保持一致 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 设置最大上传文件大小 -->
<property name="maxUploadSize" value="88888888"></property>
</bean>
【TestUploadAndDownController.java】
方式一:
@RequestMapping(value = "/up" ,method = RequestMethod.POST)
public String up (String desc, MultipartFile uploadFile, HttpSession session) throws IOException {
// 获取上传文件的名称
String filename = uploadFile.getOriginalFilename();
String path = session.getServletContext().getRealPath("phone") + File.separator + filename;
// 获取输入流
InputStream is = uploadFile.getInputStream();
// 获取输出流
File file = new File(path);
OutputStream fos = new FileOutputStream(file);
byte[] bt = new byte[1024];
int len;
while((len = is.read(bt)) != -1){
fos.write(bt, 0, len);
}
is.close();
fos.close();
return "success";
}
注意: 上传出现异常
类型 异常报告
消息 E:\IDEA\SpringMVC\SpringMVC_demo3\out\artifacts\SpringMVC_demo3_war_exploded\phone\1.jpg (系统找不到指定的路径。)
java.io.FileNotFoundException: E:\IDEA\SpringMVC\SpringMVC_demo3\out\artifacts\SpringMVC_demo3_war_exploded\phone\1.jpg (系统找不到指定的路径。)
解决方法:(以为自己的为例子)E:\IDEA\SpringMVC\SpringMVC_demo3\out\artifacts\SpringMVC_demo3_war_exploded这个目录下创建一个phone文件就可解决问题
可以在代码中写入System.out.prinln(path); 方便查看图片上传的位置
方式二:
@RequestMapping(value = "/up",method = RequestMethod.POST)
public String up (MultipartFile uploadFile, HttpSession session) throws IOException {
// 获取上传文件的名称
String filename = uploadFile.getOriginalFilename();
String finalFileName = UUID.randomUUID() + filename.substring(filename.lastIndexOf("."));
String path = session.getServletContext().getRealPath("phone") + File.separator + finalFileName;
File file = new File(path);
uploadFile.transferTo(file);
return "success";
}
3、多个文件上传
【index.jsp】
<form action="up" method="post" enctype="multipart/form-data">
头像:<input type="file" name="uploadFile"/>
头像1:<input type="file" name="uploadFile"/>
头像2:<input type="file" name="uploadFile"/>
<input type="submit" value="上传"/>
</form>
【TestUploadAndDownController.java】
@RequestMapping(value = "/up",method = RequestMethod.POST)
public String ups(MultipartFile[] uploadFile, HttpSession session) throws IOException {
for(MultipartFile uploadFiles : uploadFile){
// 判断文件是否为空
if(! uploadFiles.isEmpty()){
String filename = uploadFiles.getOriginalFilename();
String finalFileName = UUID.randomUUID() + filename.substring(filename.lastIndexOf("."));
String path = session.getServletContext().getRealPath("phone") + File.separator + finalFileName;
File file = new File(path);
uploadFiles.transferTo(file);
}
}
return "success";
}