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

I'm looking to access the Yahoo Weather API data through the JSON object's channel -> item -> forecast -> {day1} {day2} {day3} {day4} {day5}. How can I do this retrieval?

I attempted to access the forecast data but encountered issues, specifically a NullPointerException and sometimes crashes. This is because I am unable to retrieve the data from item -> forecast -> {data}. Within the Item class: condition = new ...

The issue arises when attempting to apply CSS styles to an existing component or body tag,

I am currently working on an Angular 7 project where I have a requirement to dynamically load a component using routes. However, when I try to add styles for the body tag and existing component tags in the dynamically loaded component style-sheet, they do ...

Comparing Angular i18n JSON files automatically for consistency checks

Within my Angular application, I am working with two translation files: en.json and xx.json. While the standard practice is to create translations in both files for a multilanguage application, some developers may only add translations to one file when tes ...

What steps can I take to make my animation work in the opposite direction as well?

I'm currently working with an angular slider that is set to TRUE/OPEN by default. The issue I am facing is that while I am able to slide it using angular animations in one direction, I am unable to see the transition when sliding it back. Any assistan ...

Unable to convert the String value into a java.time.LocalDate object

I am struggling with formatting the json payload for my Entity Class ImportTrans. The eventTime type is currently set to LocalDate, but I need to find a way to make it accept the json input format. { "eventId":"ep9_0579af51-4b5c", " ...

jwt io - unable to change the predefined value

Is there a way to clear the default value in the textbox on this link - , and replace it with my token? I've tried using .clear() and .sendkeys(keys.backspace()), but it's not working. Any suggestions on how to accomplish this task successfully? ...

Creating a dynamic visual experience with Angular 2: How to implement multiple font colors

I have a text area which is connected to one string, with the default text color set to white. <textarea style="background-color: black;color:#fff;" [(ngModel)]="outputText"></textarea> The connected string contains multiple variables. retur ...

The specified reference token grant value of [object Object] could not be located in the store

Currently, I am working with NestJs along with the oidc passport strategy using identityserver. Below is a snippet of the code: import { UnauthorizedException } from '@nestjs/common'; import { PassportStrategy } from '@nestjs/passport'; ...

Declare that a method alters a value with state

Here's a more streamlined version of my code. Check out my custom hook below: export const useStep = () => { const [step, setStep] = useState<Steps>("sending"); const changeStep = (newStep: Steps) => setStep(newStep); return { ste ...

When attempting to add mp3 files to a Vue/TypeScript application, a "Module not found" error is triggered

I am encountering an error while trying to import .mp3 files into my Vue/Typescript app. Upon running 'npm serve', I am presented with the following message: ERROR in /Users/***/***/application/src/components/Sampler.vue(80,16): 80:16 Cannot fin ...

Tips for providing a base URL in Angular to fetch images from an API

How do I access the API URL to retrieve images from a database? <table class="table"> <tr> <th>Id</th> <th>Image</th> </tr> ...

Tips for accessing data from a JSON file in a compiled Angular2 project

I have a scenario in my Angular2 project where I am fetching settings from a JSON file. However, after compiling the project for production using the ng build command, I noticed that the content of the JSON file is now inserted into the main.bundle.js. Thi ...

Is it feasible to alter the TypeScript interface for the default JavaScript object (JSON)?

When dealing with cyclic objects, JSON.stringify() can break (as mentioned in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value) An alternative solution suggested in the same article is to use 'cycle.js&apos ...

Tips for scrolling a div that has too much content within a webpage

Is there a method to manipulate the scrollbar within a div on a webpage? Specifically, I am attempting to automate scrolling up and down on an Instagram post like . However, since the scrollbar may be hidden using CSS properties, detecting it can be challe ...

How to Use ngFor to Create a Link for the Last Item in an Array in Angular 7

I need help with adding a link to the last item in my menu items array. Currently, the menu items are generated from a component, but I'm unsure how to make the last item in the array a clickable link. ActionMenuItem.component.html <div *ngIf= ...

In Next.js, the Typescript compiler does not halt when an error occurs

I am looking to incorporate Next.js with TypeScript into my project. I followed the official method of adding TypeScript to Next.js using npx create-next-app --typescript. Everything seemed fine, but when a TypeScript error occurs (e.g. const st: string = ...

Adjust the height, width, and color of the "kendo-switch" widget

I am looking to customize the height, width, and color of the "kendo-switch" component. I attempted to modify the element's style directly, but it did not have the desired effect. What would be the most effective approach for achieving this customiza ...

The assignment of `accessToken` is restricted in Mapbox-gl's typing

I'm currently utilizing the mapbox-gl library in conjunction with TypeScript. Moreover, I have successfully installed its type definitions that are sourced from the community using @types/mapbox-gl. However, when attempting to import and assign an acc ...

Next.js Enhanced with Google Analytics

I've been experimenting with integrating Google Analytics into Next.js, following a tutorial on YouTube - https://www.youtube.com/watch?v=lMSBNBDjaH8 Following the instructions in the video, I added these two scripts in _document.js: <script async ...

dyld: Unable to locate symbol: _node_module_register

Embarking on my Angular2 learning journey with the help of this GitHub repository: https://github.com/angular/quickstart After running npm install, I attempted to launch the project in a browser using npm start. However, I encountered the following error: ...