Angular:使用HttpClient.request()将数据上传到Springboot App时,CORS策略阻止了访问

时间:2019-01-25 08:53:58

标签: angular spring-boot cors

我正在创建代码以将文件/图像上传到服务器(春季启动),但是每次尝试时,它始终被CORS策略阻止。

我正在创建代码以将文件/图像上传到服务器(春季启动),但是每次尝试时,它始终被CORS策略阻止。

这是我的服务

pushFileToStorage(file: File): Observable<HttpEvent<{}>> {
    const formdata: FormData = new FormData();

    formdata.append('file', file);

    let hd = new HttpHeaders();
    hd = hd.append('Access-Control-Allow-Origin', 'http://xxxxx:8092');
    hd = hd.append('Content-Type', 'multipart/form-data');
    hd = hd.append('Accept', 'multipart/form-data');

    console.log(hd);

    const req = new HttpRequest('POST', 'http://xxxxx:8092/post', formdata, {
        headers: hd,
        reportProgress: true,
        responseType: 'text'
    });

    return this.http.request(req);
  }

这是我的类型

 selectedFiles: FileList;
 currentFileUpload: File;
 progress: { percentage: number } = { percentage: 0 };

 selectFile(event) {
    this.selectedFiles = event.target.files;
 }

 upload() {
    this.progress.percentage = 0;

    this.currentFileUpload = this.selectedFiles.item(0);
    this.accountService.pushFileToStorage(this.currentFileUpload).subscribe(event => {

    if (event.type === HttpEventType.UploadProgress) {
       this.progress.percentage = Math.round(100 * event.loaded / event.total);
    } else if (event instanceof HttpResponse) {
      console.log('File is completely uploaded!');
    }
    });

    this.selectedFiles = undefined;
 }

1 个答案:

答案 0 :(得分:0)

快速解答: 将@CrossOrigin(origins =“ http://localhost:4200”)添加到您的控制器方法中。