前端如何调用@RestController @RequestMapping("/excel") public class ImportController { @Resource private ExcelComponent excelComponent; @PostMapping("/import-person") public Boolean importPersonFile(@RequestParam("file") MultipartFile file) throws IOException { excelComponent.importPersonFile(file); return true; }
时间: 2023-05-31 18:04:34 浏览: 44
前端可以通过发送POST请求来调用这个接口。
具体方法如下:
1. 在前端HTML页面中,添加一个文件上传的表单,包含一个文件选择框和一个提交按钮。
2. 当用户选择文件并点击提交按钮时,前端通过JavaScript代码发送一个POST请求到后端的/import-person接口,并将文件数据作为请求参数发送给后端。
3. 后端接收到请求后,调用ExcelComponent组件的importPersonFile方法来处理上传的Excel文件。
4. 处理完成后,后端返回一个布尔值true给前端,表示文件上传成功。
5. 前端可以根据后端返回的结果来进行相应的提示或页面跳转等操作。
示例代码如下:
HTML页面部分:
```html
<form id="uploadForm" method="POST" enctype="multipart/form-data">
<input type="file" name="file" id="fileInput">
<button type="submit" id="uploadBtn">上传文件</button>
</form>
```
JavaScript代码部分:
```javascript
const form = document.getElementById('uploadForm');
const fileInput = document.getElementById('fileInput');
const uploadBtn = document.getElementById('uploadBtn');
uploadBtn.addEventListener('click', (e) => {
e.preventDefault();
const formData = new FormData();
formData.append('file', fileInput.files[0]);
fetch('/excel/import-person', {
method: 'POST',
body: formData
})
.then(res => res.json())
.then(data => {
if (data === true) {
alert('文件上传成功!');
} else {
alert('文件上传失败!');
}
})
.catch(err => {
console.log(err);
alert('文件上传失败!');
});
});
```