SpringBoot + Axios
1、文件上传
<form th:action="url" method="post" enctype="multipart/form-data">
<input type="file" name="fileInformation"/>
<input type="submit" value="上传文件"/>
</form>
/**
* 上传文件
* @return
*/
@PostMapping("upload")
public void uploadFile(MultipartFile fileInformation,HttpSession session) throws IOException {
// 获取用户的 id
User user = (User) session.getAttribute("user");
// 获取文件的原始名称
String oldFileName = fileInformation.getOriginalFilename();
// 获取文件后缀
String file_ext = "." + FilenameUtils.getExtension(fileInformation.getOriginalFilename());
// 生成新的文件名称
String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+oldFileName;
// 文件大小
long size = fileInformation.getSize();
// 文件类型
String type = fileInformation.getContentType();
// 保存文件的路径
String upload_path = ResourceUtils.getURL("classpath:").getPath() + "static/save";
// 创建日期文件夹
String dateFormat = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String dateDirPath = upload_path + "/" + dateFormat;
File dateDir = new File(dateDirPath);
if(!dateDir.exists()){
dateDir.mkdirs();
}
// 处理文件上传
fileInformation.transferTo(new File(dateDir,newFileName));
System.out.println("success");
}
2、获取数据
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
// 得到文件中的数据
axios
.get("http://localhost:8081/files/axios/getDataFromFile", {
params: {
name: "filename",
ext : "ext" // 文件后缀
},
})
.then((res) => {
console.log("数据是:", res.data);
})
.catch((e) => {
console.log("获取数据失败");
});
}
// 或者
axios({
method: "post",
url: "http://localhost:8081/files/axios/getDataFromFile",
// changeOrigin: true,
// responseType: "json",
data: { // Controller中用 @RequestBody 接收 data
name: "filename",
ext : "ext" // 文件后缀
},
})
.then(function (res) {
console.log("数据是:" + res.data);
})
@GetMapping("getDataFromFile")
public void getDataFromFile(@RequestParam String name, @RequestParam String ext,HttpServletResponse response) throws IOException {
// 获取文件路径
String filePath = ResourceUtils.getURL("classpath:").getPath() + "static/save/" + name + "." + ext;
// 获取文件输入流
FileInputStream is = new FileInputStream(new File(filePath));
// attachment --> 文件下载 inline --> 在线打开
// response.setHeader("content-disposition","attachment;fileName"+ URLEncoder.encode("application","UTF-8"));
// 获得相应输出流
ServletOutputStream os = response.getOutputStream();
// 文件拷贝
IOUtils.copy(is,os);
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
System.out.println("success");
}
<!-- 需要如下依赖-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>