4、异常处理-导入io的包
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
xml配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置默认编码格式 -->
<property name="defaultEncoding" value="utf-8" />
<!-- 设置最大上传的文件-->
<property name="maxUploadSize" value="10240000" />
</bean>
、
文件上传
<form action="api/upload" method="post" enctype="multipart/form-data">
文件上传 <br><br>
<input type="file" name="file" /> <br><br>
<input type="file" name="file" /> <br><br>
<input type="file" name="file" /> <br><br>
<input type="submit" value="提交">
</form>
@Controller
@RequestMapping("/api")
public class UploadContorller{
@RequestMapping("/upload")
public String upload(MultipartFile [] file, HttpServletRequest request){
for (int i = 0; i < file.length; i++) {
// 1. 获得上传的路径
String path = request.getServletContext().getRealPath("/upload/");
// 2. 拿到从页面上传过来的文件
String name = file[i].getOriginalFilename();
// 3.拿到的文件名改名
String newname = new Date().getTime() + new Random(999999).nextInt() + name;
// 4.上传的路径
File f = new File(path + newname);
System.out.println(f);
// 5.上传
try {
file[i].transferTo(f);
} catch (IOException e) {
e.printStackTrace();
}
}
return "show";
}
}
文件下载
<form action="api/upload" method="post" enctype="multipart/form-data">
<a href="download/aa1.zip">下载1</a>
<a href="download/sql笔试.png">下载2</a>
<a href="api/download/?fileName=sql笔试.png">下载3</a>
</form>
@Controller
@RequestMapping("/api")
public class UploadContorller{
@RequestMapping("/download")
public ResponseEntity<byte[]> downloads(@RequestParam("fileName") String fileName, HttpServletRequest request) throws IOException {
//1.下载路径
String path = request.getServletContext().getRealPath("/download/");
//2.下载的完整路径
File f = new File(path+fileName);
//3.转格式 或者 getBytes(StandardCharsets.UTF_8)
String name = new String(fileName.getBytes("utf-8"),"iso8859-1");
//4.头部信息对象 转流
HttpHeaders hh = new HttpHeaders();
hh.setContentDispositionFormData("attachment",name);
hh.setContentType(MediaType.APPLICATION_OCTET_STREAM);
// 或者用 ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), hh, HttpStatus.CREATED);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(f), hh, HttpStatus.CREATED);
}
}