前言
需要一个功能:实现网页上传按钮上传文件,后端接收到保存在本地,可以支持一个或者多个文件上传,这里我做的限制只支持上传图片文件。
一、前端
前端代码:
<button type="button" class="btn btn-block btn-primary" οnclick="uploadFiles()">上传您需要识别的图片</button>
<input type="file" id="fileInput" multiple style="display: none;" accept="image/*">
<p style="margin-top: 20px;text-align: center;font-weight: bolder">注:支持多张同时上传</p>
<script>
function uploadFiles() {
// 触发文件选择对话框
document.getElementById('fileInput').click();
}
// 处理文件选择后的操作
document.getElementById('fileInput').addEventListener('change', handleFileSelect);
function handleFileSelect(event) {
const files = event.target.files;
if (files.length > 0) {
// 创建 FormData 对象,用于包装文件数据
const formData = new FormData();
// 将文件数组追加到 FormData 中
for (let i = 0; i < files.length; i++) {
formData.append('files', files[i]);
}
// 使用 Ajax 将文件发送到后端
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/upload', true);
// 处理上传完成后的事件
xhr.onload = function () {
if (xhr.status === 200) {
alert('文件上传成功!');
} else {
alert(xhr.responseText); // 在这里展示后端返回的内容
}
};
// 发送 FormData 对象
xhr.send(formData);
}
}
</script>
二、后端
@RestController
@RequestMapping("/api")
public class FileUploadController {
@PostMapping("/upload")
public ResponseEntity<String> handleFileUpload(@RequestParam("files") MultipartFile[] files) {
try {
for (MultipartFile file : files) {
// 检查文件类型是否为图片
if (file.getContentType() != null && file.getContentType().startsWith("image")) {
// 处理图片文件
} else {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("请上传图片文件。");
}
}
}
catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("上传失败,请重试。");
}
// 获取项目的根目录
String projectRoot = System.getProperty("user.dir");
// 指定上传文件的存储路径(这里假设存储在项目根目录的 "uploads" 文件夹中)
String uploadPath = projectRoot + File.separator + "uploads" + File.separator;
try {
// 创建 "uploads" 文件夹(如果不存在)
File uploadFolder = new File(uploadPath);
if (!uploadFolder.exists()) {
uploadFolder.mkdirs();
}
// 处理文件上传逻辑
for (MultipartFile file : files) {
String fileName = file.getOriginalFilename();
// 构建目标文件对象
File targetFile = new File(uploadFolder, fileName);
// 将上传文件保存到目标文件
file.transferTo(targetFile);
}
return ResponseEntity.ok("File uploaded successfully!");
} catch (IOException e) {
e.printStackTrace();
return ResponseEntity.badRequest().body("File upload failed: " + e.getMessage());
}
}
关于上传文件的类型,需要在前端和后端做双重限制,这样才能保证只能上传指定类型的文件类型。