The upload cannot be completed as the file upload is not in a multipart request format

This file upload code was referenced from this source.

The issue lies in the fact that it is sending the request as JSON instead of multipart form data, causing the server side code to reject the request and resulting in a failed upload.

I have confirmed that the server side code is functioning properly by testing it with Postman.

Below is the HTML section:

<h1>Angular 10 FormData (multipart/form-data) Example</h1>
<div>
    <form [formGroup] = "uploadForm" (ngSubmit)="onSubmit()">      
      <div>
        <input type="file" name="profile" (change)="onFileSelect($event)" />
      </div>
      <div>
        <button type="submit">Upload</button>
      </div>
    </form>
  </div>

This is the component part:

onSubmit() {
    const formData = new FormData();
    formData.append('file', this.uploadForm.get('profile').value);

    this.http.post<any>(CommonConstants.env+"api/master/upload",formData).subscribe(
      (res) => console.log(res),
      (err) => console.log(err)
    );
  }

 onFileSelect(event) {
    if (event.target.files.length > 0) {
      const file = event.target.files[0];
      this.uploadForm.get('profile').setValue(file);
    }
  }

After uploading, I noticed that the network tab in Chrome does not display the Content-Type header in Request Headers.

https://i.stack.imgur.com/WfkY3.png

Answer №1

I found a solution by reassigning the file to a Blob variable and passing it with the formData without the multipart header. The browser automatically determines the header in this scenario.

You can try something like the following:

onSubmit() {
    const formData = new FormData();
    blob:Blob=this.uploadForm.get('profile').value
    formData.append('file', blob);

    this.http.post<any>(CommonConstants.env+"api/master/upload", formData).subscribe(
      (res) => console.log(res),
      (err) => console.log(err)
    );
  }

Answer №2

To successfully convert your file into a Blob format and add the appropriate type, you must first save the selected file as an object.

selectedFile: File = null;

Then, within your formData:

formData.append('file', new Blob([JSON.stringify(file)],{type:'application/json'}));

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

What is the process of bringing in a Svelte component into a Typescript file?

Can a Svelte component be imported into a Typescript file and successfully compiled by Rollup? While the following code works fine as a Javascript file, it encounters errors when converted to Typescript, as the TS compiler struggles with a .svelte file: i ...

Extracting event handlers using @ContentChildren: A guide

I am dealing with a my-button component that needs to be enclosed within a my-button-row component in the following manner: <my-button-row> <my-button [label]="Some Label" (click)="func1($event)"></my-button> <my-button [label ...

When using Inertia.js with Typescript, an issue arises where the argument types {} and InertiaFormProps{} are not compatible with the parameter type Partial<VisitOptions> or undefined

I set up a brand new Laravel project and integrated Laravel Breeze along with Typescript support. After creating a form (using useForm()) and utilizing the .post() method with one of the options selected (such as onFinish: () =>), I encountered the fol ...

Angular 9 Problem: Facing difficulties launching the primary application

Looking for assistance with a technical issue I am trying to set up an initial application on my Windows 10, 64-bit machine following the instructions provided in but I am encountering a problem. OS: Windows 10, 64-bit Issue: The command npm install is ...

Modifying the onclick event of a button: A guide

Once a user selects the Add button located below the photo, that specific image is to be appended to the table adjacent to the list and subsequently transforms the add button into a REMOVE button. eg. Current status: https://i.stack.imgur.com/8eJoS.png ...

Tips for implementing page-break-after:always within a bootstrap row?

I have a bootstrap row with a set of divs inside like this: @media print { p { page-break-after : always } } <div class = "row"> <div> data1 </div> <p> break page here </p> <div> data2 </div> <div> ...

What is the significance of including parameter names in Typescript function type signatures?

Just diving into typescript for the first time, so bear with me... I decided to create a simple filter function for a container I had created class Container<T> { filter(predicate: (T) => boolean): Container<T> { for(const elem ...

How do I determine in Angular (2+) when all child components have been initialized from the parent component?

Is there a lifecycle hook named "ngAfterAllChildrenInit" that can be used because ngAfterViewInit is called before the ngOninit of the children? I am currently trying to find a solution that avoids using setTimeOut or emitting events from all of the child ...

Utilizing PropTypes in React with TypeScript

I've encountered issues while trying to integrate PropTypes with Typescript: Previously, without typescript, I had successfully used: class TodoFilterItem extends Component { constructor (props) { super(props); Followed by: TodoFilterItem.prop ...

Issue with Angular: Unable to properly sort data while modifying queryParams

Within the component.ts file: export class TabsComponent implements OnInit { constructor( private store$: Store<UsersState>, private router: ActivatedRoute ) {} ngOnInit(): void { this.onFilterByIncome(); this.router.queryParam ...

What is the process for updating variable values in an angular service.ts file?

Being a newcomer to programming and the angular framework, my question may seem too obvious. I have a service.ts file that interacts with Firebase to implement CRUD operations. Inside Firebase, I have a filter function that relies on the value of the vari ...

Updating a boolean value and passing a body to an Angular HttpClient PUT request

Need help with passing a model in an API Put Request. Also, seeking guidance on including a boolean value concurrently. ...

Utilizing the useContext hook within a strictly Typescript-based class component

I have developed a pure Typescript class that serves as a utility class for performing a specific task. Within this class, I have created a context that is intended to be used universally. My goal is to utilize this context and its values within the pure T ...

angular2 ngFor is not functioning properly

I'm having an issue where I cannot get textboxes to appear whenever a user clicks a button. I am attempting to achieve this using ngFor, but for some reason, the ngFor is not iterating as expected. Even after trying to change the array reference with ...

Dispatch a websocket communication from a synchronous function and retrieve the information within the function itself

I am currently working on an Angular project and need guidance on the most effective approach to implement the following. The requirement is: To retrieve an image from the cache if available, otherwise fetch it from a web socket server. I have managed ...

After defining Partial<T>, encountering an error trying to access an undefined property is unexpected

In my function, I am attempting to standardize certain values by specifying the whole function type as Partial. However, despite declaring the interaction variable as Partial Type, I keep encountering the error message saying "Cannot read property endTime ...

Permitted the usage of a global variable of any type as the return value of a function that does not explicitly define its

Here's a snippet of TypeScript code that compiles successfully: let testVar: any; const testFunc: () => number = () => { return testVar; }; Why does this code compile without errors? What is the reasoning behind it? ...

Utilize existing *.resx translation files within a hybrid application combining AngularJS and Angular 5

Greetings! I currently have an AngularJS application that utilizes $translateProvider for internalization and WebResources.resx files: angular.module('app') .config(['$translateProvider', 'sysSettings', 'ngDialogProv ...

The information is failing to display properly within the mat-menu

Recently, I've been working on creating a navbar that includes a submenu. Even though the navigation bar data is loading properly, I am facing some issues with the submenu functionality. As a beginner in this area, I would appreciate any help or guida ...

Error in Writing Functional Components with Typescript in React

I am struggling to create a versatile functional component and encountering issues like the one shown in this https://i.stack.imgur.com/WQkKg.png: Here is the code snippet: interface IAppTable<Type> { height: number; data: Type[]; tableLayout: ...