要解决Angular 8 Springboot文件上传的问题,您可以按照以下步骤进行操作:
在Angular应用中创建一个文件上传组件,可以使用ng g component file-upload
命令生成组件。
在文件上传组件的HTML模板中,创建一个文件选择输入框和一个上传按钮:
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-file-upload',
templateUrl: './file-upload.component.html',
styleUrls: ['./file-upload.component.css']
})
export class FileUploadComponent {
selectedFile: File;
constructor(private http: HttpClient) { }
onFileSelected(files: FileList) {
this.selectedFile = files.item(0);
}
onUpload() {
const formData = new FormData();
formData.append('file', this.selectedFile);
this.http.post('/api/upload', formData).subscribe(
(response) => {
console.log('上传成功');
},
(error) => {
console.log('上传失败');
}
);
}
}
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
public class FileUploadController {
@PostMapping("/api/upload")
public void uploadFile(@RequestParam("file") MultipartFile file) {
// 处理文件上传逻辑
}
}
这样,当用户选择文件并点击上传按钮时,Angular应用将会发送一个POST请求到Spring Boot应用的/api/upload
接口,然后Spring Boot会处理文件上传逻辑。
请根据您的具体需求修改上述代码,并确保在Angular应用中正确引入HttpClient模块,Spring Boot应用中正确引入MultipartFile类。