Spring boot 使用Spring boot和angular上传文件

Spring boot 使用Spring boot和angular上传文件,spring-boot,angular8,Spring Boot,Angular8,我需要上传文件使用弹簧启动和角度 这是控制器代码,使用Postman可以很好地工作 @PostMapping("/uploadFile") public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) { String fileName = fileStorageService.storeFile(file); Strin

我需要上传文件使用弹簧启动和角度 这是控制器代码,使用Postman可以很好地工作

 @PostMapping("/uploadFile")
 public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
    String fileName = fileStorageService.storeFile(file);
    String message = "";
    String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
            .path("/downloadFile/")
            .path(fileName)
            .toUriString();

    message = "You successfully uploaded " + file.getOriginalFilename() + "!";
    return ResponseEntity.status(HttpStatus.OK).body(message);
}
-HTML代码:

 <h1>Upload and Download File</h1>
<input type="file" id="customFile" (change)="selectFile($event)">
<button class="btn btn-primary" [disabled]="!selectedFiles || admincheck || status" 
(click)="upload()">Save File</button>
上传和下载文件
保存文件
这个错误出现了

访问位于“”的XMLHttpRequesthttp://localhost:8080/uploadFile“起源”http://localhost:4200'已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在'access control Allow Origin'标头

职位http://localhost:8080/uploadFile net::ERR_失败

错误HttpErrorResponse{headers:HttpHeaders,状态:0,状态文本:“未知错误”,url:http://localhost:8080/uploadFile“,ok:false,…}

zone.js:3331 XHR加载失败:POST“http://localhost:8080/uploadFile“


我在你的代码中看到的一个主要问题,稍后你会遇到,你没有在你的代码中设置内容类型

<form method="POST" enctype="multipart/form-data" action="/">

CORS是增加安全性的web标准。你应该详细阅读。在控制器类中添加@CrossOrigin注释应该可以解决这个问题。本教程介绍了许多解决此问题的方法

 <h1>Upload and Download File</h1>
<input type="file" id="customFile" (change)="selectFile($event)">
<button class="btn btn-primary" [disabled]="!selectedFiles || admincheck || status" 
(click)="upload()">Save File</button>
<form method="POST" enctype="multipart/form-data" action="/">