Using the HTTP Post method to retrieve a file object: a step-by-step guide

Is there a way to utilize a http POST request in order to retrieve a file object? Though the uploading of files to the server using the POST request seems successful and flawless, attempting to fetch the file results in an unusual response: console output

The console output displays what the uploaded file looks like on the server. The preceding entry on the console showcases the response received when trying to access the file from the server. Could the file be corrupted?

This is the post request used for uploading a new file to the server:

formData.append('username', localStorage.getItem('username'));
formData.append('subleaseISUcookie', localStorage.getItem('subleaseISUcookie'));
if(fileCount > 0){
  formData.append('fileName', inputEl.files[0]);
  console.log(inputEl.files[0]);
  this.http.post(URL, formData).subscribe(
          res => {
              //console.log(res);
               if(!res['error']){
        console.log("no error");
      } else {
        console.log(res['error']);
      }
         //this.router.navigate(['login']);
          },
          err => {
          console.log("there was an error");
      console.log(err);
          }
        );    
}

This is how the file is fetched from the server:

import { Component, OnInit } from '@angular/core';
import { Headers, Http } from '@angular/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class ProfilePictureGrabService {

  constructor(private http: Http) { }

  currUser: string = localStorage.getItem('username');

  requestString: string = '/retrieveProfilePicture/' + this.currUser;
  getProfilePic(): Observable<any> {
    console.log(this.requestString);
    // Get the json data string
    return this.http.post( this.requestString , {
        username: localStorage.getItem('username'),
        subleaseISUcookie: localStorage.getItem('subleaseISUcookie')
    }).map(res => {

        return res;
    });
  }
  private handleError(error: any): Promise<any> {
      console.error('An error occurred', error); 
      return Promise.reject(error.message || error);
  }

}

Finally, this is how the above service is called to utilize the file object returned by the http post request:

this.profilePictureGrabService.getProfilePic().subscribe( any => {
  this.retrievePic = any;
  console.log(this.retrievePic);
});

var reader2 = new FileReader();
this.profilePic = this.retrievePic;
if(this.profilePic){
  reader2.readAsDataURL(this.profilePic);
}else{
}
reader2.onload = function(){
    (<HTMLImageElement>document.getElementById('profilePic')).src = reader2.result;
}

Answer №1

    To implement ProfilePictureGrabService functionality, follow these steps:

    import { Headers, RequestOptions } from '@angular/http';
    @Injectable()
    export class ProfilePictureGrabService {
        headers: any;
        options: any
      constructor(private http: Http) {

           this.headers = new Headers({ 'Content-Type': 'text/plain' });
            this.options = new RequestOptions({ headers: this.headers }); 
         }

currUser: string = localStorage.getItem('username');

  requestString: string = '/retrieveProfilePicture/' + this.currUser;
  getProfilePic(): Observable<any> {
    console.log(this.requestString);
    // Obtain the json data string
    return this.http.post( this.requestString , {
        username: localStorage.getItem('username'),
        subleaseISUcookie: localStorage.getItem('subleaseISUcookie')
    },this.options).map(res => {

        return res;
    });
  }

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

What is the best way to load a component every time the function is called?

Currently, I am utilizing Angular and endeavoring to create reusable actions such as bulk updates, deletes, and deactivations. I have incorporated all of these actions into another component and aim to use it as a generic method. This implies that I have ...

The pairing of Transpiller and Internet Explorer 8 is like a dynamic

In starting my new project, I am considering using BabelJS. However, there is a significant requirement that must be met: it needs to be compatible with IE8. ISSUE: Babel compiles ES6 to ES5, but the support for ES5 on IE8 is lacking. Are there any alter ...

Capable of retrieving response data, however, the label remains invisible in the dropdown menu

Upon selecting a country, I expect the corresponding city from the database to be automatically displayed in the dropdown menu. While I was able to retrieve the state response (as seen in the console output), it is not appearing in the dropdown menu. Inte ...

"Optimize Your Data with PrimeNG's Table Filtering Feature

I'm currently working on implementing a filter table using PrimeNG, but I'm facing an issue with the JSON structure I receive, which has multiple nested levels. Here's an example: { "id": "123", "category": "nice", "place": { "ran ...

Creating a Personalized Color Palette Naming System with Material UI in TypeScript

I have been working on incorporating a custom color palette into my material ui theme. Following the guidance provided in the Material UI documentation available here Material UI Docs, I am trying to implement this feature. Here is an excerpt from my cod ...

Angular 2 Mixup: Using Leaflet and Google Maps with Incorrect Tile Order

I am encountering an issue while working on Leaflet and Google within Angular 2. The problem lies in the Tilemill tiles not rendering properly as they are displaying in a strange order. Here is a screenshot of the current state: https://i.stack.imgur.com/ ...

Sending JSON data stored in $scope using AngularJS with AJAXPOST request

I am frustrated: I am currently working on an AngularJS project and struggling to correctly post data. I have filled out some HTML input fields, with values stored in a variable like $scope.product, and now I need to send this JSON structure of $scope.pro ...

Angular7 & Electron: Resolving the Issue of Loading Local Resources

I am encountering difficulties while working with electron. Although I can successfully load my project using ng serve, I encounter an error when attempting to open it with electron as shown in the developer tools Not allowed to load local resource: fil ...

The manager encountered an issue while querying for "Photo" data: EntityMetadataNotFoundError - no metadata could be found

I encountered an error while attempting to utilize typeorm on express: if (!metadata) throw new EntityMetadataNotFoundError(target) ^ EntityMetadataNotFoundError: Unable to locate metadata for "Photo". Below is my data source: import " ...

What is the best way to manage the connections in my D3 tree chart?

I've been working on customizing a tool from an open source library called angular-d3-tree, but I'm struggling with getting the links to connect properly in my D3 tree structure. This is what my current tree layout looks like: https://i.stack.im ...

In Visual Studio Code, beautification feature splits HTML attributes onto separate lines, improving readability and code organization. Unfortunately, the print width setting does not apply

I have done extensive research and tried numerous solutions, When using Angular and formatting HTML with Prettier, it appears quite messy as it wraps each attribute to a new line, for example: <button pButton class="btn" ...

Angular: The Ultimate Guide to Reloading a Specific Section of HTML (Form/Div/Table)

On my create operation page, I have a form with two fields. When I reload the page using window.reload in code, I can see updates in the form. However, I want to trigger a refresh on the form by clicking a button. I need help writing a function that can r ...

Utilizing AWS CDK to Define StackProps Input Variables

Recently, I have started using the AWS CDK and encountered a challenge. I want to allow end users to define custom input variables when using my AWS CDK without having to edit the entire code. While I have been able to work with standard types such as stri ...

Having trouble with reloading the FirebaseAuth widget in an Angular 8 single page application?

I recently developed an Angular 8 CLI project that integrates with FirebaseUI Auth for email and password login. However, I am facing an issue where the FirebaseUI Auth widget does not appear after the user logs out. Is this a bug in the system or am I ove ...

Description: TypeScript type that derives from the third constructor parameter of a generic function

How can I determine the type of constructor props for a generic type? Take a look at this example. type PatchableProps<T> = T extends { [k: string | number]: any } ? { [Key in keyof T]: PatchableProps<T[Key]> } : T | Patch export class ...

communication between flutter and nodejs may encounter issues receiving requests

having trouble finding a solution from my code where I attempted to send data from Flutter to express.js this is my Flutter code: try{ var regbody={ "username":username, "fullname":fullname, "password":p ...

Stop redux useSelector from causing unnecessary re-renders

I'm working on a component in React-Redux that utilizes the useSelector hook to retrieve a dictionary from the Redux store. This dictionary maps UUIDs to objects containing data that I need to display. interface IComponentProps { id: string } const ...

Error encountered with the root reducer due to data type mismatch

Within my Redux store setup, I have a persistedReducer initialized to include the redux-persist config and the "rootReducer": client/src/redux/store.ts: import { configureStore } from '@reduxjs/toolkit'; import { persistStore, persistReducer } f ...

Tips for utilizing jest.mock following the removal of @types/jest (^jest@24)

After upgrading from version 7 to version 8 of @angular-builders/jest, I followed the instructions provided in the migration guide which advised removing @types/jest since it now comes bundled with Jest v24. Additionally, changes were made to my tsconfig a ...

Disabling the Parent Component Form Submit button until the child component fields are deemed valid

I'm currently utilizing a Template Driven Form. HTML of the Parent Component <form #BasicForm="ngForm" (ngSubmit)="onBasicDetailsSubmit()" id="BasicForm"> <app-input-text [(sharedVar)]="dashboardDetails.Text1" [isMandatory]="true" >&l ...