📅  最后修改于: 2023-12-03 14:39:12.185000             🧑  作者: Mango
本示例为Angular和Spring结合实现文件上传的示例,该示例展示了如何实现将用户上传的文件保存到服务器上的步骤。
<input #fileInput type="file" (change)="onFileSelected()" accept=".jpg,.jpeg,.png">
onFileSelected() {
const file: File = this.fileInput.nativeElement.files[0];
this.uploadFile(file);
}
uploadFile(file: File) {
const formData = new FormData();
formData.append('file', file);
this.http.post<any>('http://localhost:8080/api/upload', formData).subscribe(
(response) => console.log(response),
(error) => console.log(error)
);
}
@RestController
@RequestMapping("/api")
public class FileUploadController {
@PostMapping("/upload")
public ResponseEntity<String> fileUpload(@RequestParam("file") MultipartFile file) {
try {
byte[] bytes = file.getBytes();
Path path = Paths.get("/uploads/" + file.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Upload failed");
}
return ResponseEntity.ok("Upload successful");
}
}
@Configuration
public class MultipartConfig {
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
factory.setMaxFileSize(DataSize.parse("10MB"));
factory.setMaxRequestSize(DataSize.parse("10MB"));
return factory.createMultipartConfig();
}
}
CREATE TABLE `uploads` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`file_name` varchar(255) NOT NULL,
`file_type` varchar(45) DEFAULT NULL,
`file_size` bigint(20) DEFAULT NULL,
`upload_time` datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
总结一下,这个示例应该能够帮助你了解如何使用Angular和Spring实现文件上传的功能。需要注意一些安全性问题,例如在后端应用程序中使用一些限制来防止上传过大的文件,以及仅上传安全文件类型。希望本文对您有所帮助。