Cannot upload the same file to both Spring and Angular twice

Having trouble uploading the same file twice. However, it works fine when uploading different files.

Encountering an error under the Network tab in Chrome

{ timeStamp: ......, status: 417
  error: 'Bad Request',
  message: 'Required request part 'file' is not present'
  path: 'url as hosted on Tomcat'
}

Controller.java file for Spring Boot

@PostMapping("/Post")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") 
MultipartFile file){ String Message=""; try .......(and so on)}

Angular Component Code

<form [formGroup]="uploadForm" (ngSubmit) = "onSubmit()">
<input type="file" id="selectFile" formControlName="file1" name="selectFile"
(change)="fileEvent($event)"/>

<input type="submit" name="Submit"/>
</form>

Component.ts file

fileEvent(e) {
 this.data = e.target.files[0];
}
onSubmit() {
  let headers: any = new Headers();
  headers.append('Content-type', 'undefined');
  let formData = new FormData();
  formData.append("file", this.data);
  const req5 = new HttpRequest('POST', 'url as hosted on TOMCAT', formData,
  reportProgress: true,
  responseType: 'text'
  });
  return this.httpClient.request(req5).subscribe(e => {(
  console.log(e);
  )}
}

Can you point out where I might be going wrong?

Answer №1

It seems like your issue could be related to browser caching, where the first request goes through fine but the second one encounters an error. To address this problem, you can try adding a random query parameter at the end of the POST URL, for example:

var url = 'url hosted on TOMCAT';
url = url + (new Date()).getTime();

Although it might be unconventional to include a query parameter in a POST request, there should be no obstacles preventing you from doing so. This approach should help you prevent browser caching issues.

Answer №2

It seems likely that the issue stems from the change-listener on the input field not triggering again for the same file, and your this.data being set to null after the initial submission.

To resolve this, you can manually reset the field like so:

onSubmit() {
    // upload the file ...
    document.getElementById("selectFile").value = "";
}

This method may not be ideal when using Angular. Alternatively, you can reset the form by:

onSubmit() {
    // upload the file ...
    this.uploadForm.reset();
}

View the same answer in German

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

Using NodeJS to perform asynchronous tasks with setImmediate while also incorporating private class

Today marks my first time experimenting with setImmediate. I've come to realize that it may not be able to run private class methods. Can someone shed some light on this? Why is that the case? Not Functioning Properly When trying to use a private cl ...

Limit the types of function parameters to only one option within a union type parameter

I have a collection of tuples that I can use to define variables: type KnownPair = ["dog", "paws"] | ["fish", "scales"]; const goodPair: KnownPair = ["dog", "paws"]; //@ts-expect-error you cannot mix them: const badPair: KnownPair = ["dog", "scales"]; I ...

Error message retrieval in Liferay fails due to malfunctioning Ajax listener

While working on a project using liferay jsf, I encountered an issue with inserting <f:ajax listener="#{jsfController.searchValidDestination}"> within <h:selectOneMenu/> in my view page. The problem is that I am not getting any result from the ...

What is the reason behind In-memory-web-api not generating an ID?

While I have successfully implemented the GET, PUT, and DELETE methods using InMemoryDbService to simulate an API, I am facing issues with the CREATE method. It seems like the ID is not being generated in the route to display my add form. The error message ...

Deploying an Angular application on AWS EC2 without using nginx as a reverse proxy

Our team has been tackling the challenge of hosting an Angular application on AWS. A question has emerged: can we deploy the Angular application without relying on nginx? This inquiry arose when we successfully deployed a node.js application without any ...

Tips on customizing KendoUI-Dialog titlebar using CSS for a single component

I am struggling with styling the KENDO UI dialog in a unique way: Imagine I have a component named WatComponent. Inside this component, When the user clicks the "Forbidden" button, my goal is to make a warning styled dialog appear, with a yellow/orange ...

Tips for fixing the error message "unable to access property 'property-name' of null"

I need assistance with retrieving data from a firebase database and storing it in an array using typescript. Below is the code snippet I am working with: export class ViewUserPage { public list = []; public ref = firebase.database().ref(); public ...

Angular 2 and beyond: delivering a unified global service instance for sub-modules

Exploring how to create a comprehensive service that can be accessed from submodules within an angular 2+ application is key. While the traditional component hierarchy setup works well for this, understanding the process when dealing with multiple modules ...

Optimizing Performance for MySQL's "Select Distinct" Function

In my Java application, I have the following code snippet: // Method #1 String sql = "select distinct ID from X inner join Y on ... where ..." List<String> ids = jdbcTemplate.queryForList(query, String.class); Currently, I am retrieving a list of d ...

Angular 5 does not allow function calls within decorators

I encountered an issue while building a Progressive Web App (PWA) from my Angular application. When running ng build --prod, I received the following error: ERROR in app\app.module.ts(108,64): Error during template compile of 'AppModule' Fu ...

What is the method to define a loosely typed object literal in a TypeScript declaration?

We are currently in the process of creating TypeScript definitions for a library called args-js, which is designed to parse query strings and provide the results in an object literal format. For example: ?name=miriam&age=26 This input will produce th ...

Adding JSON content to a form for editing functionality within an Angular 8 CRUD application

I am currently working on building a Single Page Application using Angular 8 for the frontend and Laravel for the backend. I have been able to successfully pass data to the backend via JWT, and everything is functioning as expected. The application follows ...

What is the best way to retrieve information from my Angular 2 component while I am already within my Kendo Grid?

After creating a new row in my grid, I encounter an issue with accessing other information within my component. Typically, I would use "this.method" or "this.property" to access these details. However, post-creating the row, "this" no longer references t ...

Using JavaFX to create a TreeTableView with nodes of varying sizes

I need assistance with styling TreeTableViews and their rows. I have set up a treetableview showcasing objects named Component, divided into classes A, B, and C. In my setup, B objects are nested within A, and C objects are nested within B objects. While I ...

Eslint is back and it's cracking down on unused variables with no

I've configured eslint to alert me about unused variables rules: { '@typescript-eslint/no-unused-vars': ['error', { args: 'none' }], } Presently, I have a TypeScript class structured like this: import { User } from &ap ...

Upgrading my loop React component from vanilla JavaScript to TypeScript for improved efficiency and functionality

After seeking assistance from Stack Overflow, I successfully created a loop in React using a functional component that works as intended. However, I am encountering errors while trying to refactor the loop to TypeScript. The code for my DetailedProduct c ...

Error: unable to access cordova in Ionic 2Another wording for this error message could be:

While running my Ionic app using the command ionic serve -l, I encountered the following error message: Runtime Error Uncaught (in promise): cordova_not_available Stack Error: Uncaught (in promise): cordova_not_available at v (http://localhost:8100/bu ...

Refreshing a page with a 404 error in Angular 2 while in production mode and without the useHash configuration

I've encountered an issue while using Angular 2 without the useHash feature. When trying to visit the URL directly in a browser, I'm getting a 404 not found error. I have searched extensively and attempted various solutions including: Adding L ...

The property 'dateClick' is not found in the 'CalendarOptions' type in version 6 of fullcalendar

Below is the Angular code snippet I am currently using: calendarOptions: CalendarOptions = { plugins: [ dayGridPlugin, timeGridPlugin, listPlugin ], initialView: 'dayGridMonth', headerToolbar: { left: 'prev today next' ...

Class for Eliminating the Background Image Using Bootstrap

Is there a Bootstrap class that can be used to remove a background image from a div? Currently, I have this style defined in my CSS: background-image: linear-gradient(to bottom, rgba(0,0,0,0.1), rgba(0,0,0,0)); I would like to remove it using: bg-img-non ...