1.导入web依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2.先创建一个HTML文件
提交方式为post提交,接口为/file/upload
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>单文件上传</title>
</head>
<body>
<form action="/file/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
3.创建一个FileController类
@RequestMapping("/upload")
public String upload(@RequestParam("file")MultipartFile file){
//获取原始名称
String fileName=file.getOriginalFilename();
//获取后缀名
assert fileName != null;
String suffixName=fileName.substring(fileName.lastIndexOf("."));
//文件保存路径
String filePath="d:/file/";
//文件重命名,防止重复
fileName=filePath+ UUID.randomUUID()+fileName;
//文件对象
File dest=new File(fileName);
//判断路径是否存在,如果不存在则创建
if (!dest.getParentFile().exists()){
dest.getParentFile().mkdir();
}
try {
//保存到服务器中
file.transferTo(dest);
return "上传成功";
} catch (IOException e) {
throw new RuntimeException(e);
}
}
4.在浏览器中输入localhost:8080/upload.html
然后点击选择文件
选择完文件之后点击提交,这是就上传到浏览器当中了,在刚才设置的文件路径里面也有这个文件了