1. 前端页面
<form>
记得设置一下enctype = "multipart/form-data"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>04-文件上传</title>
</head>
<body>
<form action="http://localhost:8080/upload" method="post" enctype="multipart/form-data" align="center">
<h2>请选择你的文件进行上传吧</h2>
<input type="file" name="file" multiple> <br>
<input type="submit" value="上传!~">
</form>
</body>
</html>
2. 后端核心代码
后端的Controller中接收的类型是MultipartFile
@RestController
public class UploadController {
@PostMapping("/upload")
public static Result upload(@RequestParam("file") MultipartFile file) {
// public static final String targetFilePath = "E:\\MyDownLoad";
String des = HtmlConstant.targetFilePath + File.separator + file.getOriginalFilename();
FileOutputStream fos = null;
try {
// 1. 获取输入流
InputStream inputStream = file.getInputStream();
// 2. 创建file
File newFile = new File(des);
// 3. 获取输出流
fos = new FileOutputStream(newFile);
// 4. 使用工具类进行写入
IOUtils.copy(inputStream, fos);
} catch (IOException e) {
e.printStackTrace();
return Result.fail("上传失败,请联系管理员");
}finally {
try {
fos.close(); // 记得关闭,不然文件写入可能不会完成。
} catch (IOException e) {
e.printStackTrace();
}
}
return Result.ok("上传成功了~");
}
}
3. 其他代码
这里创建了一个DTO (Data Transfer Object) 数据传输对象
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result {
private Boolean success;
private String errorMsg;
private Object data;
public static Result ok(){
return new Result( true,null,null);
}
public static Result ok(Object data) {
return new Result(true, null, data);
}
public static Result fail(String errorMsg) {
return new Result(false, errorMsg, null);
}
}