用js写一个简单的文件上传 后端用springboot
前端代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
</head>
<body>
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" name="file">
<button type="submit">上传</button>
</form>
<script>
const form = document.getElementById('uploadForm');
form.addEventListener('submit', async (event) => {
event.preventDefault();
const file = form.file.files[0];
const formData = new FormData();
formData.append('file', file);
const response = await fetch('/upload', {
method: 'POST',
body: formData
});
const result = await response.json();
console.log(result);
});
</script>
</body>
</html>
后端代码:
@RestController
public class FileController {
@PostMapping("/upload")
public Map<String, Object> upload(@RequestParam("file") MultipartFile file) {
Map<String, Object> result = new HashMap<>();
try {
// 保存文件到服务器
String fileName = file.getOriginalFilename();
String filePath = "/tmp/" + fileName;
File dest = new File(filePath);
file.transferTo(dest);
// 返回成功信息
result.put("success", true);
result.put("message", "文件上传成功");
} catch (IOException e) {
// 返回失败信息
result.put("success", false);
result.put("message", "文件上传失败");
}
return result;
}
}
注意事项:
- 前端需要使用
FormData对象来上传文件。 - 后端需要使用
MultipartFile对象来接收文件。 - 在上传成功或失败后,需要将结果以 JSON 格式返回给前端
原文地址: https://www.cveoy.top/t/topic/egOa 著作权归作者所有。请勿转载和采集!