Bonjour à tous. je suis confronté à une erreur lors de l'upload de fichier. Il faut noter qu'avec le swagger, l'upload marche mais avec mon interface conçu avec angular, j'ai l'erreur suivante :
l'extrait de mes codes aux fins de recevoir votre aideAccess to XMLHttpRequest at 'http://127.0.0.1:8081/api/fichier/create/1/1' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
main.js:1563 HttpErrorResponse*{headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://127.0.0.1:8081/api/fichier/create/1/1", ok: false,*…}
main.js:1610 df
L'entete du fichierCOntroller Spring boot
La fonction spring boot permettant d'uploader un fichier et qui prend en paramètre aussi deux valeurs
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5 @RestController @CrossOrigin(origins = "*") @RequestMapping(path = "/api/fichier",headers="content-type=multipart/*")
Mon code service typescript coté client
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6 @PostMapping("/create/{id_parent}/{id_typeFichier}") @ApiOperation(value = "Enregistrer un fichier") public ResponseEntity<?> uploadFile(@PathVariable(name = "id_parent") Long id_parent, @PathVariable(name = "id_typeFichier") Long id_typeFichier, @RequestParam("file") MultipartFile file) { String fileName = fileStorageService.storeFile(file);
Mon code TS
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12 uploadService(file:File,id_parent :number,id_typeFichier:number) { const headers = new Headers({ 'Content-Type': 'multipart/form-data' }); const uploadURL = this.host + 'fichier/create/'+id_parent+'/'+id_typeFichier; const formData: FormData = new FormData(); formData.append('file',file); return this.http.post<any>(uploadURL, { headers: headers, "Content-Type": "multipart/form-data", "file": formData }); }
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 onDocumentFileSelect(event:any) { if (this.documentFiles.length === 0) { this.documentFiles.push(...event.addedFiles); } else { // this.notificationService.warn(`Vous ne pouvez choisir qu'un seul fichier.`); return; } const file = this.documentFiles[0]; console.log(file) // Send file const formData = this.firstFormGroup.value; //const formData = new FormData(); //formData.append("file", file,file.name); console.log(this.typefichier.id); this.fichierService.uploadService(this.file,formData.id_parcelle,this.typefichier.id).subscribe((message:string) => { console.log(message); //this.notificationService.success(`Document chargé avec succès`); console.log("sucess"); } , error => { console.log(error); this.showError(); }) //this.initForm(); ; }
Partager