Ensuring a User has an Image in MySQL Using Angular 6

As part of my development process, I am working on creating a new user and sending their information along with an image to a MySQL database. The process involves sending a user object with form data through the following component.ts file:

subscribeUser() {
this.errorMessage = "";
if (this.subscribeForm.invalid) {
  this.errorMessage = "cannot create user with empty fields";
  return;
}
this.userService.createUser(this.user, this.selectedFile)
  .subscribe(data => {
    console.log(data);
    this.router.navigate(['/login']);
  }, error => {
    console.log(error);
  });
 }
   public onFileChanged(event) {
console.log(event);
this.selectedFile = event.target.files[0];
console.log(this.selectedFile);
}

The logic for creating the user is handled in the service.ts file:

createUser(user: User, file: File) { 
let formData: FormData = new FormData(); 
const userBlob = new Blob([JSON.stringify({
"firstname": user.firstname,
"lastname": user.lastname,
"mail": user.mail,
"password": user.password
})],{ type: "application/json"});
formData.append('file', file); 
formData.append('user', userBlob);
return this.http.post<User>(AppSettings.APP_URL + "/users/new", formData,{responseType:'text' as 'json'});
}

The controller.java file handles the request processing:

@PostMapping(value="/",
        produces = MediaType.APPLICATION_JSON_VALUE,
        consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.MULTIPART_FORM_DATA_VALUE,"multipart/form-data"}))
public ResponseEntity createUser(@RequestPart("file") MultipartFile file, @RequestPart("user") User user) throws IOException {

    if(user == null){
        return ResponseEntity.badRequest().body("cannot create user with empty fields");
    }
   
    User createdUser = userRepository.save(user);
    return ResponseEntity.ok(createdUser);
}

The component.html file contains the form structure for user registration:

  <form [formGroup]="subscribeForm" (ngSubmit)="subscribeUser()" novalidate>
  <div class="form-group">
    <label for="formGroupExampleInput">Nom</label>
    <input type="text" class="form-control" id="firstname" [(ngModel)]="user.firstname" name="firstname" placeholder="Nom" formControlName="nom">
  </div>
  <div class="form-group">
    <label for="formGroupExampleInput2">Prénom</label>
    <input type="text" class="form-control" id="lastname" [(ngModel)]="user.lastname" name="lastname" placeholder="Prenom" formControlName="prenom">
  </div>
  <div class="form-group">
    <label for="formGroupExampleInput3">Email</label>
    <input type="text" class="form-control" id="mail" [(ngModel)]="user.mail" placeholder="Email" name="mail" formControlName="mail" >
  </div>
  <div class="form-group">
    <label for="formGroupExampleInput4">Password</label>
    <input type="text" class="form-control" id="password" [(ngModel)]="user.password" placeholder="Password" formControlName="password" >
  </div>
  <div class="form-group">
  <input type="file" [(ngModel)]="user.photo" (change)="onFileChanged($event)"></div>
    <button class="btn btn-primary"  type="submit">Register</button>
</form>

An error is encountered while processing the request:

"Content type 'application/octet-stream' not supported"

Thank you

Answer №1

Have you thought about converting the image type from File to BLOB?

Furthermore, in the REST Controller, you can handle it as MultipartFile.

Edit: the error message you are receiving

"Content type 'application/octet-stream' not supported"

It appears that the issue may be related to your header mime type (refer to this mime type guide)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I exclude the 'node_modules' directory but still include specific subfiles in the tsconfig file for TypeScript?

My tsconfig file is structured as follows: { "compileOnSave": false, "compilerOptions": { "module": "es2015", "target": "es2015", "sourceMap": true, "jsx": "react", "allowSyntheticDefaultImports": true, "noImplicitAny": false, ...

Angular - calculate the total of numerical values within a nested *ngFor loop

Looking to extract numerical values from an array of objects, where each object contains specific data within arrays. I attempted using *ngFor to iterate through the values, but instead of summing them up, they are concatenated together. Here's a brie ...

Utilizing Selenium WebDriver to Locate Elements Using Relative XPath Based on Their Text Content

I am currently utilizing Selenium webdriver in conjunction with Java. My main challenge lies in identifying elements within dynamic dropdown lists, as accessing them by exact id/name/xpath is proving to be difficult. I have resorted to locating these elem ...

Exploring Angular 2 Tabs: Navigating Through Child Components

Recently, I've been experimenting with trying to access the HTML elements within tabs components using an example from the Angular 2 docs. You can view the example here. Here is a snippet of my implementation: import {Component, ElementRef, Inj ...

How can I extract just the initial 2 letters of a country name using AmCharts maps?

Having trouble with Amcharts maps. I have a map that displays countries as United States, but I only want them to show as US. Is there a country formatter available for this issue? Any help is appreciated. ...

Guide on exporting type definitions and utilizing them with npm link for a local package

I am in the process of developing a new testing tool called tepper as an alternative to supertest. My goal is to make this package available in both ESM and CJS formats. However, I'm encountering an issue where users of the library are unable to locat ...

Encountering difficulty importing TypeScript files dynamically within a Deno executable

When attempting to import a file from aws in an exe using its public link based on user input, I am facing difficulties For example, I generated my exe with the command below deno compile --allow-all main.ts Users execute this exe using commands like ./e ...

Having trouble with @viewChild not activating the modal popup and displaying an error message stating that triggerModal is not a function in

I am facing an issue where the click event is not being triggered from the parent component to display a Bootstrap 3 modal. I am getting the following error: ERROR TypeError: this.target.triggerModal is not a function This is what I have done so far: Pa ...

Discover the syntax for reading route parameters in Angular

Currently, I am integrating the Paypal API into my project. After confirming a purchase, Paypal redirects to a specified URL. I set the desired URL as "localhost:4200/shop/order". However, when Paypal returns the URL, it appends the token and payerid at th ...

Navigating through nested JSON Objects for dropdown functionality in Angular 6 - a step-by-step guide

Currently, I am facing a challenge in Angular 6.0 where I am trying to use HttpClient to iterate through JSON data retrieved from a local file within my assets folder. Below is the sample JSON Data: [{ "configKey": [{ "user1": [{ ...

There seems to be an issue with Firebase authentication on firebase-admin in node.js. Your client is being denied permission to access the URL "system.gserviceaccount.com" from the server

Issue I've been utilizing Firebase auth on my client and using firebase-admin to verify on the server. It was functioning well until I decided to migrate to a different server, which caused it to stop working. The crucial part of the error message i ...

Obtain the ViewContainerRef object from the Component

Looking to create nested components in Angular 4? This is the Chooser Component import {InputComponent} from './input/input.component' import {BlockComponent} from './block/block.component' export const FormChooser = { Block: Block ...

Converting React to Typescript and refactoring it leads to an issue where the property 'readOnly' is not recognized on the type 'IntrinsicAttributes & InputProps & { children?: ReactNode; }'

I'm currently in the process of refactoring an application using Typescript. Everything is going smoothly except for one particular component. I am utilizing the Input component from the library material-ui. import {Input} from "material-ui"; class ...

Having trouble locating the Selenium element on the webpage?

I am encountering an issue with Selenium during a click event WebElement btn = driver.findElement(By.xpath("//form[@name=\"addMemberForm\"]/div[14]/div/button")); System.out.print(btn); The output of the print statement [[ChromeDriver: chro ...

typescript defining callback parameter type based on callback arguments

function funcOneCustom<T extends boolean = false>(isTrue: T) { type RETURN = T extends true ? string : number; return (isTrue ? "Nice" : 20) as RETURN; } function funcCbCustom<T>(cb: (isTrue: boolean) => T) { const getFirst = () => ...

What is the process for accessing a website using Java programming language?

Currently, I have a jar file up for sale that requires users to sign up on a particular website in order to download it. My issue lies in wanting to verify if purchasers have a valid login for the site when they run the jar file. Despite my attempts with h ...

Set the default page for the p-table

My English proficiency is lacking. I am currently using a p-table with pagination, but I need to modify the pagination in the HTML code. <p-table #dt [columns]="cols" [value]="values" [paginator]="true" [rows]="10" (onFilter)="filtra ...

Information within specified dates shows all leaders

Looking to filter data based on Start Date, End Date, and HeadName. The current search query successfully filters between dates but does not properly filter the HeadName column, displaying all results instead. Sno HeadName Date Amount BillNo BillD ...

Adding data from a database into an object in PHP for temporary use during the loading process can be achieved by following

I'm a beginner in PHP and I have some code that retrieves category type data from a database. I want to temporarily store this data in a PHP object while the page is loading. Initially, I need to load all predefined data and then use it when a certain ...

Adjusting the transparency of TabBadge in Ionic 2

I am currently working on a project that involves tabs, and I'm looking to update the style of the badge when the value is 0. Unfortunately, I am unsure how to dynamically change the style of my tabs or adjust the opacity of the badge in the style. M ...