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

Integration of SSR is not possible in an ongoing Spartacus project

Recently, I attempted to integrate SSR mode into my existing Spartacus project using the following command: ng g @spartacus/schematics:add-ssr However, this action resulted in the following error message: ✅️ Added 'ts-loader' into devDep ...

TypeScript - ESBuild - Encountered an unexpected '<' token

When compiling TypeScript files for a React app with esbuild, everything goes smoothly. However, upon checking the browser console, an error pops up: An unexpected token '<' is causing errors after the return statement // components/editor/ ...

Issue: Typescript/React module does not have any exported components

I'm currently facing an issue with exporting prop types from one view component to another container component and using them as state type definitions: // ./Component.tsx export type Props { someProp: string; } export const Component = (props: ...

Combining pixijs with TypeScript in Ionic 2 using npm

To begin, I ran the command npm install -g ionic Followed by ionic start pixiApp blank --v2 Navigated to the pixiApp directory with cd pixiApp Installed necessary dependencies using npm install Added a specific version of pixi.js (4.1.0) with npm install p ...

What are some strategies I can implement to effectively manage different errors and ensure the app does not crash

I came across a variety of solutions for error handling. The key concept revolves around this explanation: https://angular.io/api/core/ErrorHandler Attempts were made to implement it in order to capture TypeError, however, the outcome was not successful: ...

Ways to simulate a service using get() method with a particular data structure

I've been working on writing unit tests for my component and simulating a service that makes HTTP requests. The response data structure looks like this: { ContactActivityView :[ { Code:"AB", IsActive:false, }, ...

Content from PHP's unlink() function continues to persistently display

I run an Angular front end along with a PHP back end for my website. I utilize PHP's unlink function to remove specific images from Angular's assets folder: $fileToDelete = "../src/assets/images/".$name; unlink($fileToDelete) or die("Error delet ...

React Typescript can easily differentiate between various prop types by selecting either of the two types

I am working with two Typescript interfaces: type ISecond = { timeType: string secondTime: number } type IDay = { timeType: string startTime: number endTime: number } When it comes to my react function props types, ... const CountDown ...

The type 'void | Observable<User>' does not include the property 'subscribe'. Error code: ts(2339)

authenticate() { this.auth.authenticate(this.username, this.password).subscribe((_: any) => { this.router.navigateByUrl('dashboard', {replaceUrl: true}); }); } I'm puzzled by this error message, I've tried a few solu ...

`The validation in Angular 12 is successful, yet the mat-input remains invalid.`

Code snippet of Component- ngOnInit(): void { this.form = this.fb.group({ currentPassword: ['', [Validators.required], [this.matchCurrentPassword]], newPassword: ['', [Validators.required, Validators.minL ...

The object's key values were unexpectedly empty despite containing data

There's an issue with my object - it initially gets key values, but then suddenly loses them all. All the key values become empty and a message appears in the console for the object: "this value was evaluated upon first expanding. it may have ch ...

Troubleshooting issue: Webpack dev server's Hot Module Replacement not functioning correctly when

I've been working on a Vue 2 application that is mostly JavaScript, and now I am looking to incorporate some new TypeScript modules and components into it. Everything runs smoothly when I start the webpack dev server. However, whenever I make a chang ...

Obtain form data as an object in Vue when passed in as a slot

Currently, I am working on developing a wizard tool that allows users to create their own wizards in the following format: <wiz> <form> <page> <label /> <input /> </page> <page> <label /> ...

Steer clear of using inline styling when designing with Mui V5

I firmly believe that separating styling from code enhances the clarity and cleanliness of the code. Personally, I have always viewed using inline styling (style={{}}) as a bad practice. In Mui V4, it was simple - I would create a styles file and import i ...

I'm experiencing a strange issue where my React component renders twice in production mode, despite having strict mode turned off. Can anyone advise me on

Within my layout.tsx, I have a structure that encloses the page with a container div and introduces a separately defined TopBar component alongside. The functionality seems fine, but an issue arises where the component is created before the {children}, as ...

The trouble with React Navigation encountered with TypeScript: This Entity Cannot Be Invoked

Currently, I'm facing a typescript issue after upgrading to React Navigation 5. The specific error message reads: There is an issue with calling this expression. The union type '{ <RouteName extends "Stack1Screen1" | "Home&quo ...

Ways to resolve a 404 error on a live Angular application being hosted by NGINX

I am encountering an issue with my deployed application on a server where every time I refresh a specific page, I receive a NGINX 404 error. The application is running within Docker. Below is the configuration file for NGINX. server { listen 80; locat ...

Utilizing a Material UI custom theme in React with Typescript: A step-by-step guide

Upon using the tool , I received a js file and a json file following the paths mentioned on the theme generator page: // src/ui/theme/index.js /* src/ui/theme/theme.json */ The files operate smoothly when left with the .js extension. However, when I attem ...

Tips for adjusting the width of ng2 smart table columns

Here is an example of my three columns, showcasing the ability to customize width sizes. modifyPassword: { title: this.gridTittle["Modify Password"], type: 'custom', renderComponent: UserPasswordChangeComponent, filter: false }, ...

Bringing in the Ionic ToastController to a TypeScript class

I'm unsure if it's feasible or wise, but I am currently developing an Ionic 3 project and I want to encapsulate "Toast" functionality within a class so that I can define default values and access it from any part of the application. Is there a ...