Uploading Files or Images in Angular 6 Using Spring Boot

I need assistance or recommendations

---------------#################---------------

Is there a way to upload an image in a form using formcontrolName? Any suggestions would be appreciated.

------------###########################---------------------

I have been attempting to upload an image file along with other information such as firstname, lastname and file and it is functioning correctly:

/* File Upload request  to Upload file  */
this.currentFileUpload = this.selectedFiles.item(0);
let formdata: FormData = new FormData();
formdata.append('firstName', "Harkesh");
formdata.append('lastName', "kumar");
formdata.append('file', this.currentFileUpload);

However, my issue lies in sending a FORM file along with a string and an Object, as FormData does not accept the latter:

let formdata: FormData = new FormData();
formdata.append('functionId', this.functionId);
formdata.append('processId', this.processId);
formdata.append('file', this.currentFileUpload);
formdata.append('formDetails', userobjArr);

A second option I am exploring:

let formdata: FormData = new FormData();
formdata.append('file', this.currentFileUpload);

userDetails.name = "";
userobjWrapper["functionId"] = this.functionId;
userobjWrapper["processId"] = this.processId;
userobjWrapper["taskId"] = this.taskId;
userobjWrapper["file"] = this.currentFileUpload;
userobjWrapper["formDetails"] = userobjArr;

userobjArr is an array of Objects that I assign to formDetails, which ends up with a value of null.

I am uncertain about how to fetch an image in one rest Service API call. For the REST API, I am utilizing a Spring Boot Rest Controller.

Any ideas on how to proceed would be greatly appreciated.

Answer №1

Here is a suggestion for you :)

onImageUploadChange(event) {
    const self = this;
    const target = event.target || event.srcElement;
    const files = target.files;
    let imgPath = files[0].name;
    imgPath = imgPath.split('.');
    if ((imgPath[1] === 'png') || (imgPath[1] === 'PNG')) {
      const xhttp = new XMLHttpRequest();
      const formData = new FormData();
      console.log('uploadingImage');
      formData.append('imageFile', files[0]);
      xhttp.onreadystatechange = function () {
        event.target.value = null;
        if (this.readyState === 4) {
          if (this.status === 201) {
            console.log('imageUploadedSuccessfully');
          } else {
            console.log('imageUploadFailed')));
          }
        }
      };
      xhttp.open('post', '/formatimages', true);
      xhttp.setRequestHeader('Pragma', 'no-cache');
      xhttp.send(formData);
    } else {
      console.log('uploadFailedInvalidImage')));
    }
  }
}

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

Obtain the default/initial argument type of typescript for extension purposes

Currently, I am in the process of developing code that automatically generates type hints based on function calls related to GraphQL Nexus tasks. In one of its functions, it requires an anonymous type constructed from the attributes generated automaticall ...

What is the title of this specific switch operator syntax?

I keep coming across this type of switch statement in a codebase and cannot seem to find any documentation on it. Is there a specific name for this syntax? import React from 'react' enum Options { FirstOption = 'first', SecondO ...

How can we avoid printing out undefined data from an Observable in Angular 2?

Here is the code I have in my service: fetchUserData(userId: string): Observable<any> { return this.http.get('https://jsonplaceholder.typicode.com/todos/' + userId) .map((response: Response) => { const userData = ...

The module "node_modules/puppeteer/lib/types" does not contain the export "Cookie"

Currently facing an issue with puppeteer types. I am attempting to import the Cookie type, but it seems to be not functioning on versions above 6.0.0. import { Cookie } from 'puppeteer'; Here is the error message: /node_modules/puppeteer/lib/typ ...

Error: No provider found for _HttpClient in the NullInjector context

Hello everyone, I am new to Angular and currently facing an issue that has me stuck. The error message I'm receiving is as follows: ERROR NullInjectorError: R3InjectorError(Standalone[_AppComponent])[_ApiCallServiceService -> _ApiCallServiceService ...

Upon hovering, icons for each project name are displayed when `mouseenter` event is triggered

My issue lies with the mouseenter function. I am trying to display icons specific to the project name I hover over, but currently, it displays icons for all projects at once. I want each project hovered over to show me its respective icons Below is some c ...

Innovative approaches to enhancing Feathers services through the use of relational data in design patterns

I'm in the process of developing a straightforward application that involves a one-to-many relationship between data entities. Specifically, I am working with feathers js and sequelize (utilizing sqlite) to create a system where each site can have mul ...

Utilizing the filter function to sort users in React using Next.js and TypeScript

I am currently working on my frontend app using next.js and typescript. My goal is to filter an array to display only the users that match a search query, similar to a search bar. However, I keep getting back undefined results. Let me share a snippet of m ...

Access data in an array using a specific index in Typescript

Here is the JSON format I am working with: { "records": [ { "ID": "4", "TYPE": "landscape", "FIMAGE": "viewveni.jpg", "COUNT": "4444" } ], "pagination": { "count": 1, "page": 1, "limit": 10, "totalpages": 1 } } I'm facing a challenge trying to retri ...

The intermingling of two Generics can lead to an unexpectedly deep and potentially limitless Type instantiation

My experience with Typescript is still new, and I could use some guidance in resolving the error message Type instantiation is excessively deep and possibly infinite.(2589) You can access the playground here. To identify the error, uncomment the Type Exp ...

The concept of overloaded function types in TypeScript

Is it possible to create an overloaded function type without specifying a concrete function? By examining the type of an overloaded function, it appears that using multiple call signatures on an interface or object type is the recommended approach: functi ...

Having an excess of 32 individual byte values

My current project involves developing a permission system using bitwise operators. A question came up regarding the limitation of having only 32 permissions in place: enum permissions { none = 0, Founder = 1 << 0, SeeAdmins = 1 << ...

Changing an array of objects into an object containing two arrays in TypeScript

I am dealing with an input array of objects [ { col1: 'col1value1', col2: 'col2value1', col3: col1value3}, { col1: 'col1value2', col2: 'col2value2', col3: col1value2} ] My goal is to transform this into two arra ...

I'm struggling to transfer information from my form to TypeScript in Angular

Currently, I am working on developing a fullstack application using Node.js and Angular (material UI). However, I have encountered an issue that I need help with. I am trying to figure out how to retrieve data from an Angular form for a small web resource ...

How is it possible that this is not causing a syntax or compile-time error?

Oops! I made a mistake and typed : instead of = on line 2 of this code snippet. Why does Typescript allow this error? Isn't colon supposed to indicate a known Type for a property declaration? I'm pretty sure there's a reason encoded in the ...

Adding headers to json-server: Step-by-step guide

I am currently facing a situation where my frontend and backend are located on different servers, requiring me to make cross-domain requests. Specifically, I am using angular2 on localhost:4200, while also utilizing json-server on localhost:3000. The serv ...

``There is a pesky jQuery bug causing the page to unexpectedly refresh upon submitting an

Having issues with AJAX form submission. Here is a snippet of the code: $("#content").html("<form id='requestInfo'>............</form"); This code places a form inside a div with an id=content. Another piece of the code: $("#request ...

Top Recommendations: Comparing Standalone Components and Modules in Angular Version 14

I'm in need of some clarification on the most effective practices when it comes to utilizing standalone components and modules within Angular 14. With the introduction of standalone components as a new concept in Angular, I am seeking factual guidance ...

Closing the form and then trying to reopen it results in a crash

Loading loadingForm = new Loading(); private void btnSend_Click(object sender, EventArgs e) { Thread loading = new Thread(new ThreadStart(startLoading)); loading.Start(); new Thread(() => sendEmail() ...

How can you change the name of a component in Angular2 CLI?

If I were to create a component called 'Car', but later decided to change its name to 'Bicycle', is there a convenient way to do this quickly through the command line interface (CLI)? This includes changing the file names, class names, ...