The request was denied due to the absence of a multipart boundary in angular+spring

I am currently facing an issue with uploading a file that was recently downloaded using Angular2 to a Spring API Rest.

The problem being displayed on the Spring app is as follows...

The request was rejected because no multipart boundary was found

at org.apache.tomcat.util.http.fileupload.FileUploadBase$FileItemIteratorImpl.(FileUploadBase.java:831) ~[tomcat-embed-core-8.5.28.jar:8.5.28] at org.apache.tomcat.util.http.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:256) ~[tomcat-embed-core-8.5.28.jar:8.5.28] at org.apache.tomcat.util.http.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:280) ~[tomcat-embed-core-8.5.28.jar:8.5.28] at org.apache.catalina.connector.Request.parseParts(Request.java:2869) ~[tomcat-embed-core-8.5.28.jar:8.5.28] at org.apache.catalina.connector.Request.parseParameters(Request.java:3216) ~[tomcat-embed-core-8.5.28.jar:8.5.28] at org.apache.catalina.connector.Request.getParameter(Request.java:1137) ~[tomcat-embed-core-8.5.28.jar:8.5.28]

The client side sends the request with "multipart/form-data" as the content-type.

How can this issue be resolved?

fileDownloaderService

upload(file) {
const formData = new FormData();
formData.append('file', file);
    const req = new HttpRequest('POST', this.urlUpload, file, {
      headers: new HttpHeaders({'Content-Type':'multipart/form-data'}),
      reportProgress: true
    });
    return this.http.request(req);
  }

app.component

  upload() {
     let file = this.generate_dummy_file(50000000);
     this.downloader.upload(file).subscribe( event => {
        if (event.type === HttpEventType.UploadProgress) {
        } else if (event instanceof HttpResponse) {
          console.log('File is completly uploaded!');
        }
      });


    }

  generate_dummy_file(size) {
    return new Blob([new ArrayBuffer(size)], {type: 'multipart/form-data'});
  };

And spring side

@PostMapping("/uploadFile")
    public UploadFileResponse uploadFile(@RequestParam("file") MultipartFile file) {
        return ...;
    }

Thank you for your assistance

Answer №1

Give this a shot:

 const form = new FormData();
 form.append("file", file);
 form.append("reportProgress", true);

Utilize HttpClient for this purpose,

 return this.httpclient.post(this.urlUpload, form);

Answer №2

Did you remember to include the Content-Type in your headers? If so, it's recommended to remove it for this specific request.

headers:{
        "Content-Type":"multipart/form-data", // consider removing
},

Front End:

 const formData = new FormData();
    formData.append("file", file);
    formData.append("reportProgress", "true");

return this.http.post<void>(this.API_URL + '/upload', formData);

backend end :

 @Operation(description = "Upload File")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "201", description = "File Uploaded successfully"),
            @ApiResponse(responseCode = "400", description = "Problem during file upload ")
    })
    @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseStatus(value = HttpStatus.CREATED)
    public void upload(@RequestPart("file") final MultipartFile file) {
        //action;
    }

Answer №3

Have you tried sending the data using FormData to your server?

You may want to try encapsulating the file within a FormData object so that the HttpClient can automatically handle the multipart boundaries.

uploadFile(file) {
    const formData = new FormData();
    formData.append('file', file);
    const request = new HttpRequest('POST', this.uploadUrl, formData, {
      headers: new HttpHeaders({'Content-Type':'multipart/form-data'}),
      reportProgress: true
    });
    return this.http.request(request);
  }

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

Tips for displaying dataJsonArray values in an AngularJS view

There is a JSON array stored in $scope.dataObj: $scope.dataObj={ "dataElementCode": dataelementCode, "indicator": indicator, "categoryoptioncombo": categoryoptioncombo, "attributeoptioncombo": attributeoptioncombo, "value": value, "catId": cat ...

Alert: Attempting to access an undefined value in an indexed type

I would like to find a way in Typescript to create a hashmap with indexable types that includes a warning when the value could potentially be undefined during a lookup. Is there a solution for this issue? interface HashMap { [index: number]: string; } ...

Display a pdf stream within a fresh window

I have a PDF document generated on the server that I need to display on the client side. The code on the server looks like this: ByteArrayOutputStream baos = generatePDF(); response.setContentType("application/pdf"); response.setHeader("Content-Dispositio ...

Analyzing and extracting data from nested objects using Retrofit

I have received the following JSON response: http://pastebin.com/Qir7eNsP In my project, I have a class called User public class User { private int id; @SerializedName("count_messages") private int countMessages; @SerializedName("count_followers") pr ...

Understanding and extracting information from a JSON array of objects using the Gson library

I am encountering an issue with gson while attempting to parse a JSON file that contains an array of objects. The error message "Exception in thread "main" com.google.gson.JsonSyntaxException: java.io.EOFException: End of input at line 1 column 2" is being ...

The type does not contain a property named `sort`

"The error message 'Property sort does not exist on type (and then shoes4men | shoes4women | shoes4kids)' pops up when attempting to use category.sort(). I find it puzzling since I can successfully work with count and add a thousand separato ...

Utilizing Gson to deserialize a list of Java objects containing new elements with missing IDs

Within my tree structure consisting of ol and li elements, I am dynamically adding new elements. However, when attempting to deserialize them into a Java object, an error occurs: SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/ ...

The most secure method for retrieving User Id in AngularFire2

I'm currently facing a dilemma in determining the most secure method to obtain an authenticated user's uid using AngularFire2. There seem to be two viable approaches available, but I am uncertain about which one offers the best security measures ...

What is the significance of the exclamation mark in Vue Property Decorator?

As I continue to explore the integration of TypeScript with Vue, I have encountered a query about the declaration found in the Vue property decorator documentation. @Prop({ default: 'default value' }) readonly propB!: string ...

Looking to troubleshoot an error in my TypeScript reducer implementation. How can I fix this issue?

I'm currently using typescript along with react, redux, and typessafe-actions. However, I've come across a particular error that I need help with. The error message reads: "No overload matches this call. Overload 1 of 2, '(...items: Concat ...

When using npm link, it searches for the module in the src directory rather than the dist directory

In my experience with Angular CLI Builder, I have implemented a custom builder to extend the asset configuration in angular.json for libraries that have their own assets. To manage my workspace, I utilized nrwl. I created an Angular CLI builder library an ...

Exploring the depths of Spring's RestClient and Jackson libraries with nested JSON objects

I am working with a rest client that is expected to receive JSON data from an endpoint. My goal is to extract only the information within the data[] array. { "responseStatus": "SUCCESS", "responseDetails": { "limit": 1000, "offset" ...

Creating a hierarchical visualization in Angular using a JSON object array

I'm currently working on creating a hierarchical view of users. My ultimate goal is to utilize this hierarchy view or something similar. The challenge lies in how the JSON objects used to construct the hierarchy are structured. Here's an example ...

GSON - Decoding JSON Obtained through Wikipedia API with Dynamic Object Naming

{ "batchcomplete": "uniqueText123", "continue": { "grncontinue": "0.262157292819|0.262157407383|17998004|0", "continue": "grncontinue||" }, "query": { "pages": { "54321098": { "pageid": 54321098, "ns": 1, ...

Angular 2's @ViewChild directive may sometimes yield undefined results

After consulting various related posts and documentation, I am still struggling to achieve the desired outcome with @ViewChild. My main objective is to adjust the scroll position of a div. This particular element is not a component, but a regular div in m ...

405 we're sorry, but the POST method is not allowed on this page. This page does

I'm currently working on a small Form using the kit feature Actions. However, I'm facing an issue when trying to submit the form - I keep receiving a "405 POST method not allowed. No actions exist for this page" error message. My code is quite st ...

What could be causing the HTTP response Array length in Angular to be undefined?

Currently, I am facing an issue while retrieving lobby data from a Spring Boot API to display it in my Angular frontend. After fetching the data and mapping it into an object array, I encountered a problem where the length of the array turned out to be und ...

Material-UI: Tips for aligning pagination button in the center

My attempt to implement Pagination using Material-UI went well, but now I am struggling to center the arrow buttons and page numbers. I initially tried centering them by wrapping them in a <div style={{textAlign: "center"}}>, however this ...

ts:Accessing the state within a Redux store

In my rootReducer, I have a collection of normal reducers and slice reducers. To access the state inside these reducers, I am using the useSelector hook. Here is my store setup : const store = configureStore({reducer : rootReducer}); Main Reducer: const ...

libGDX: game coming to a standstill when initiating server hosting

Looking to implement a daily bonus feature similar to that found in other games, I decided to utilize the commons-net-3.6 library from Apache to retrieve the current time from the internet. Here is the code I used: NTPUDPClient timeClient = new NTPUDPClie ...