Uploading Files with Angular 2 using AJAX and Multipart Requests

I am currently working with Angular 2 and Spring MVC. At the moment, I have an Upload component that sends an AJAX request to the Spring backend and receives a response containing parsed data from a .csv file.

export class UploadComponent {

uploadFile: function(){

var resp = this;

var data = $('input[type="file"]')[0].files[0];
this.fileupl = data;
var fd = new FormData();
fd.append("file", data);
$.ajax({
url: "uploadFile",
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(response) {
resp.response = response;
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage);
}
});
};
}

Although this solution works and provides a valid response, I'm curious if there is a more angular 2 approach to pass files to Spring and handle the response. I've been exploring the option of creating an injectable service and using subscribe, but I'm facing challenges in receiving the response.

Answer №1

Here's how I tackled the task:

import { Component, Injectable } from '@angular/core';
import { Observable} from 'rxjs/Rx';
const URL = 'myuploadURL';

@Component({
  selector: 'upload',  
  templateUrl: 'upload.component.html',
  styleUrls: ['upload.component.css']
})

export class UploadComponent {

filetoUpload: Array<File>;
response: {};

constructor() {
  this.filetoUpload = [];
}

upload() {
        this.makeFileRequest(URL, [], this.filetoUpload).then((result) => {           
            this.response = result;            
        }, (error) => {
            console.error(error);
        });
    }
fileChangeEvent(fileInput: any){
        this.filetoUpload = <Array<File>> fileInput.target.files;
    }

    makeFileRequest(url: string, params: Array<string>, files: Array<File>) {
        return new Promise((resolve, reject) => {
            let formData: any = new FormData();
            let xhr = new XMLHttpRequest();
            for(let i =0; i < files.length; i++) {
                formData.append("file", files[i], files[i].name);                
            }            

            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        resolve(JSON.parse(xhr.response));                        
                    } else {
                        reject(xhr.response);
                    }
                }
            };
            xhr.open("POST", url, true);
            xhr.send(formData);
        });
    }

}

To display the response in my HTML, I can do the following:

<div class="input-group">
                <input type="file" id="file" name="file" placeholder="select file" (change)="fileChangeEvent($event)">

                <input type="submit" value="upload" (click)="upload()" class="btn btn-primary">
        </div>


    <div *ngIf="response">

    <div class="alert alert-success" role="alert">
    <strong>{{response.myResponseObjectProperty | number}}</strong> returned successfully!
    </div>

This setup supports multiple file uploads and I turned it into an injectable service showcased in this plunkr example: https://plnkr.co/edit/wkydlC0dhDXxDuzyiDO3

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

Determining the location of an input field in Angular

I am currently utilizing Angular for my project. Within the framework, I have a primary component called name.component.ts/html. By utilizing this base component, I have created four additional components - first-name.component.ts/html, last-name, middle-n ...

What steps should I take to implement Role-Based Access Control in my Spring/React application?

I am currently working on integrating an Admin Dashboard React Bootstrap Template with a separate REST API built using Spring to query a Postgres DB. The frontend fetches data from this API. My main challenge is implementing different user roles that wi ...

Showing PHP array in the JavaScript console

I have a straightforward AJAX script that sends 3 variables to an external PHP script. The external script then adds them into an array and sends the array back. I want to output this array in the JavaScript console to check if the variables are being pass ...

The onclick handler fails to function following the injection of html using jquery AJAX

After using ajax to inject HTML into my page, the onclick handler on a specific part of that injected HTML does not seem to be functioning... Specifically, I am referring to this image... < img class="close_row" src="img/close.gif"/> In jQuery, I ...

Develop a custom library within an Angular project without using Angular framework

I am looking to create a typescript library within my Angular project that I plan to later publish on npm. I have discovered that in Angular 6, the command ng generate library can be used to generate an npm-ready library, allowing for simultaneous developm ...

Include a header in the API HTTP call for Angular 2 and Ionic 2

Working on my Ionic 2 app, I am using Angular 2 Http to retrieve JSON from an API. However, I am struggling to send the app-id, app-key, and Accept as headers in the main code snippet below: import {Component} from '@angular/core'; import {NavC ...

How do I use [(ngModel)] to set custom multiple select with 'selected' options with Angular and Materialize CSS?

Below is a snippet of code I am working with: <div class="input-field col s12"> <select name="uniqueName" [(ngModel)]="model.servicesIds" multiple> <ng-container *ngFor="let service o ...

Guidelines for implementing more rigorous type checks in TypeScript:

I am looking to enhance the code validation process and eliminate any implicit 'any' types. To achieve this, I have set "strict": true in my tsconfig.json. { "compilerOptions": { "target": "ES5", ...

Performing database insertions iteratively using a foreach loop and executing various functions in a specific order

I seem to have encountered a bug in my code, and I'm having trouble pinpointing the source of the error. Currently, I am working on developing a cart system that is designed to insert multiple pieces of data into a database upon submission from a car ...

File handling in Angular 2 using Typescript involves understanding the fundamental syntax for managing files

Would someone be able to explain the fundamental syntax for reading and writing text files, also known as file handling in TypeScript? If there is a corresponding link that anyone could provide, it would be greatly appreciated. ...

Different categories combined into a singular category

Trying to define a type that can be one of two options, currently attempting the following: type TestConfig = { file: string; name: string; } type CakeConfig = { run: string; } type MixConfig = { test: TestConfig | CakeConfig }; const typeCheck: M ...

"Encountering a challenge with accessing the class or id of an HTML element following the retrieval of data from an

Having trouble accessing the id or class of the label fetched from PHP... Here is my code snippet: $.ajax({ type:'POST', url:"<?php echo base_url(); ?>main/user_list", data:"", async:false, success: ...

What could be causing the ExcelJs plugin to malfunction in Internet Explorer 11?

My current setup involves Angular 9 and excelJs 4.1.1, which works perfectly in Chrome but throws an error in IE11 stating: "Invalid range in character set" in polyfills-es5.js Surprisingly, when I remove this dependency from package.json, everything func ...

What are some strategies for speeding up CRUD operations in a Django app that uses Ajax and Json? Is the sluggishness related to handling 7000 records, and if so, what steps can be taken

I am currently working with a remote legacy MySQL database that contains around 7000 records. The Update / Delete / Create operations are taking approximately 1.5 minutes to complete. I have imported the necessary files which are not included in Views.py b ...

What is the best way to simultaneously test/send multiple (simulated) ajax-requests to a (node.js) server?

Have you ever wondered what would happen to the memory usage and overall speed of response in your (node.js) app when fifty people use it simultaneously? Testing this scenario can be quite enlightening. I believe that there must be some convenient tools a ...

Issues with implementing routing children in Angular 8

Currently, I am in the process of building a website and facing some issues with implementing the admin section. Within my admin module, I have various components such as login, dashboard, products, etc. However, I am encountering an issue where the childr ...

How can I adjust a number using a shifter in JavaScript?

Searching for an event handler where I can use a shifter to adjust the value of a number by moving it left or right. Would appreciate any links to documentation on how to achieve this. Many thanks UPDATE Thanks to the suggestions from other users, I hav ...

Issue encountered during unit testing: "Error occurred: 'Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1'"

I am encountering an issue while trying to perform unit testing on a service. The error that I am seeing when running the test is: Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1 at MapSubscriber.project (auth.service ...

RxJS pipe operation ignoring observable

Currently, I am in the process of transitioning an app from Promises to RxJS and I could use some guidance on whether I am heading in the right direction. Situation: I have a ModalComponent that appears when an HTTP request is sent and disappears once the ...

"Implementing a feature in Angular to automatically include a blank mat-option in all non-required mat-select elements

Is there a way to dynamically add an empty mat-option to all not required mat-select elements in my application? For example: <mat-form-field appearance="outline"> <mat-label>HMO</mat-label> <mat-select> ...