我是Angular和Sping Boot 的新手,目前正在做一个涉及上传文件的项目。我已经使用Sping Boot 设置了后端,使用Angular设置了前端,但我遇到了文件上传过程的问题。我用Postman测试了backeend,一切顺利,但与前端的连接不好,它返回500内部服务器错误
这里是一个照片与错误从控制台:
enter image description here
Sping Boot 控制器:
@PostMapping("/upload")
public ResponseEntity<List<String>> uploadFiles(@RequestParam("files")List<MultipartFile> multipartFiles) throws IOException {
List<String> filenames = new ArrayList<>();
for(MultipartFile file : multipartFiles) {
String filename = StringUtils.cleanPath(file.getOriginalFilename());
Path fileStorage = get(DIRECTORY, filename).toAbsolutePath().normalize();
copy(file.getInputStream(), fileStorage, REPLACE_EXISTING);
filenames.add(filename);
}
return ResponseEntity.ok().body(filenames);
}
字符串
超文本标记语言:
<div class="upload-box">
<form class="form-inline" method="POST" enctype="multipart/form-data">
<div class="form-group">
<div class="icon">
<i class="fa-solid fa-2x fa-file-arrow-up"></i>
<p>Select your PDF file or drop it here</p>
</div>
<input class="select" type="file" class="form-control" id="pdfile" placeholder="file" accept="application/pdf" name="pdfFile"(change)="onSelectFile($event)" multiple>
</div>
<div class="button">
<input class="submit" type="submit" value="Upload Pdf" (click)="uploadFile()">
</div>
</form>
</div>
型
TS:
onSelectFile(event: any): void {
this.selectedFiles= event.target?.files;
}
uploadFile() {
if (this.selectedFiles.length == 0) {
console.log('No files selected.');
return;
}
const formData = new FormData();
for (const file of this.selectedFiles) {
formData.append('files', file);
}
this.dataService.upload(formData).subscribe(
event => {
console.log(event);
this.reportProgress(event);
},
error => {
console.error(error);
}
);
}
型
售后服务:
uploadFile(files: File) {
const formData = new FormData();
formData.append('files', files, files.name);
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'multipart/form-data'
})
};
return this.http.post<any>(this.apiUrl2 + 'file/upload', formData, httpOptions);
}
型
1条答案
按热度按时间x7yiwoj41#
尝试删除头,这对我来说是有效的,还准备了一次服务本身内部的表单数据。
组件
字符串
服务
型