一、单文件上传做法:
上传文件其实就是复制粘贴的一个过程:
- 字面意思:比如上传文件A,就是将文件A复制,然后粘贴到你要存放的位置 。
- 实际操作:就是读写的过程,将文件A通过IO流中的输入流读到java程序中,然后java程序通过输出流写入到文件B中。
- 其中, A.transferTo(B)的意思就是A转移到B中,transfer()方法已经帮我们做好底层的操作(输入流,输出流)。
1. 新建一个html文件
file.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data" action="http://localhost:8080/singlefile" >
文件:<input type="file" name="file"/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
注意:如果该html是放在服务器上跑的话,<form>表单里的action路径既可以是相对路径,也可以是绝对路径;但是,如果不放在服务器上面,而是单独出来的话,action中的路径必须是绝对路径。
2. 开启一个springboot项目,新建一个SingleFileController.java
@Controller
public class SingleFileController {
@RequestMapping("/singlefile")
@ResponseBody
public String singleFile(@RequestParam("file") MultipartFile file){
//1、判断是否为空
if(file.isEmpty()){
return "文件不能为空";
}
String fileName = file.getOriginalFilename();
int size = (int)file.getSize();
System.out.println(fileName+"---"+size);
//2、找到要存放的位置
String path = "D:/upload";
File dest = new File(path + "/" + fileName);
if(!dest.getParentFile().exists()){
dest.getParentFile().mkdirs();
}
try {
//3、保存文件,将file文件保存到dest文件中
file.transferTo(dest);
return "upload success";
} catch (IOException e) {
e.printStackTrace();
return "fail";
}
}
}
二、多文件上传
多文件上传就是把单文件上传重复多几遍,就是循环的过程
1. file.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="http://localhost:8080/multifile" method="post" enctype="multipart/form-data" >
<p>选择文件1: <input type="file" name="fileName"/></p>
<p>选择文件2: <input type="file" name="fileName"/></p>
<p>选择文件3: <input type="file" name="fileName"/></p>
<p><input type="submit" value="提交"/></p>
</form>
</body>
</html>
2. 控制层
@RequestMapping("/multifile")
@ResponseBody
public String multifile(HttpServletRequest request){
List<MultipartFile> fileList = ((MultipartHttpServletRequest)request).getFiles("fileName");
if(fileList.isEmpty()){
return "false";
}
String path = "D:/upload";
for(MultipartFile file:fileList){
String fileName = file.getOriginalFilename();
File dest = new File(path+"/"+fileName);
//判断文件父目录是否存在
if(!dest.getParentFile().exists()){
dest.getParentFile().mkdir();
}
try {
file.transferTo(dest);
} catch (IOException e) {
e.printStackTrace();
}
}
return "success";
}