i’m trying to build a project in Angular and Java where i upload a file from the frontend interface to a mysql database through the backend built in spring boot.
When i upload the file from postman it works.
When i upload it from the frontend i get the following error:
org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
I’m probably seeting some properties at the frontend in the wrong way,
Here’s the angular service’s code from where i upload the file:
@Injectable({
providedIn: 'root'
})
export class PostFileServiceService {
constructor(private http: HttpClient) { }
public postFile(name: string, size: any, type: any): Observable<any>{
const body = JSON.stringify({name, size, type});
const Options = {
headers: new HttpHeaders({
'content-type':'multipart/form-data', 'boundary':'----WebKitFormBoundaryG8vpVejPYc8E16By'
})
}
const url = `http://localhost:8080/api/v1/file/upload?name=${name}&size=${size}&type=${type}`;
return this.http.post(url, body, Options);
}
}
Here’s the code from the controller class in Java where i manage the calls to the backend:
@RestController
@RequestMapping(path="api/v1/file")
@CrossOrigin(origins = "http://localhost:4200")
public class filecontroller {
@Autowired
private final FileSystemStorageService filesService;
public filecontroller(FileSystemStorageService filesService) {
this.filesService = filesService;
}
@PostMapping("/upload")
public ResponseEntity<responseMessage> uploadFiles(@RequestParam MultipartFile file){
String message = "";
try{
filesService.store(file);
message = "File Uploaded successfully: "+file.getOriginalFilename();
return ResponseEntity.status(HttpStatus.OK).body(new responseMessage(message));
}catch (Exception e){
message = "Could not upload the file: "+file.getOriginalFilename() + "!";
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new responseMessage(message));
}
}
@GetMapping("/files")
public ResponseEntity<List<fileResponse>> getListFiles(){
List<fileResponse> files = filesService.getAllFiles().map(dbFile->{
String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath().path("/files/").path(dbFile.getId()).toUriString();
return new fileResponse(dbFile.getFileName(), dbFile.getFileSize().length, dbFile.getType(), fileDownloadUri);
}).collect(Collectors.toList());
return ResponseEntity.status(HttpStatus.OK).body(files);
}
@GetMapping("/files/{id}")
public ResponseEntity<byte[]> getFile(@PathVariable String id){
fileToUpload file = filesService.getFile(id);
return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""+file.getFileName()+"\"").body(file.getFileSize());
}
}
Where am i doing something wrong?
If you need some other code snippet please ask me.
You need to sign in to view this answers