Having trouble with uploading the profile image in Angular 2? The upload process doesn't

I just started learning Angular and decided to create a profile page. But, I encountered an error while trying to upload a profile image. The error message that I received was POST http://localhost:3000/api/v1/users/avatar/jja 500 (Internal Server Error). Upon checking the network tab, it showed me this message: {"error":"No file found"}.

Below you'll find the code snippet:

profile.ts

public onFormSubmit({ value, valid }: { value: any, valid: boolean }) {
    let profile = JSON.parse(localStorage.getItem("profile"));
    this.accountDetails = profile.user;
    this.user = value;
    this.api.post("/users/avatar/" + this.accountDetails.username, value, true)
      .subscribe((response) => {
        this.api.get("/users/" + this.accountDetails.username, true)
          .subscribe((response) => {
            profile.user = response.data
            console.log(this.accountDetails.username)
            localStorage.setItem("profile", JSON.stringify(profile))

            this.accountDetails = profile.user;
            this.user = this.accountDetails;
            console.log("2", this.user)
            location.href = "/profile"
          }, (err) => {
            alert("Update failed " + err);
          })
      }, (err) => {
        alert("Update failed " + err);
      })
  }

profile.html

<div class="col-md-3">
                    <form novalidate (ngSubmit)="onFormSubmit(imageUpload)" #imageUpload="ngForm">
                      <div class="profile-pic" style="background-image: url('http://www.sheffield.com/wp-content/uploads/2013/06/placeholder.png')"
                      >
                      {{accountDetails.avatarUrl}}
                      </div>
                    <input type="file"
                        placholder="Change Image"
                          name="avatarUrl"
                          [(ngModel)] = "user.avatarUrl" 
                          #avatarUrl = "ngModel">
                          <p  class="form-submit ">
                              <input  type="submit" value="Update" class="button color small submit">
                            </p>

                    </form>
                  </div>

Answer №1

To upload a file using Angular models, you cannot simply upload the file directly. Instead, you must either use FormData or convert the file to base64 before uploading the profile picture.

Below is an example of how you can convert a file to base64:

readFileData(file: File): void {
        var _this = this;

        if (file) {
          let fileModel: FileModel = new FileModel();
          fileModel.fileType = file.type;
          fileModel.fileName = file.name;
          fileModel.fileExtension = '';

          if (file.name.lastIndexOf(".") >= 0) {
            fileModel.fileExtension = file.name.substr(file.name.lastIndexOf(".") + 1);
          }
          fileModel.fileSize = file.size;

          var reader = new FileReader();
          reader.readAsBinaryString(file);

          reader.onload = function(e) {
            _this._handleReaderLoaded(fileModel, e);
          }
}

_handleReaderLoaded(fileModel: FileModel, readerEvt): void {
        let binaryString = readerEvt.target.result;
        fileModel.base64String = btoa(binaryString);
      }

On the backend, you will need to convert the base64 string back to a file.

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

The Angular service retrieves only the default values

I'm currently following an Angular tutorial and encountering some issues. Problem #1: The problem arises when using two services, recipe.service.ts (handles local data manipulation) and data-storage.service.ts (stores data in Firebase). When the getR ...

The "ng2-CKEditor" package is experiencing compatibility issues with TypeScript in Angular 2

Currently, I am in the process of setting up CKEditor in my angular2 application. My backend platform is node.js and for this purpose, I am utilizing the ng2-CKEditor npm module. Below, you can find snippets from respective files. index.html:: <html& ...

Struggling to pass images from express to Angular6

Snippet of Node.js code app.use('/static/images',express.static(path.join(__dirname,'images'))) Folder Structure |-root | -images When attempting to fetch data in my Angular6+ application, I am utilizing the following ...

The expansion feature of PrimeNG Turbotable

I'm currently facing an issue with the Primeng Turbotable where I am unable to expand all rows by default. You can find a code example of my problem at this link. I have already tried implementing the solution provided in this example, but unfortuna ...

What is the process of converting a byte array into a blob using JavaScript specifically for Angular?

When I receive an excel file from the backend as a byte array, my goal is to convert it into a blob and then save it as a file. Below is the code snippet that demonstrates how I achieve this: this.getFile().subscribe((response) => { const byteArra ...

The absence of the google-services.json file has rendered the Google Services Plugin inoperable. Attempted search location:

Having an issue while trying to integrate my app with Firebase. The error message keeps indicating: > File google-services.json is missing. For a more detailed view of the error, please refer to the image below: https://i.stack.imgur.com/sgNYu.jpg D ...

Angular 2 Login Component Featuring Customizable Templates

Currently, I have set up an AppModule with a variety of components, including the AppComponent which serves as the template component with the router-outlet directive. I am looking to create an AuthModule that includes its own template AuthComponent situa ...

Tips for importing a file with a dynamic path in Angular 6

I'm facing an issue where I need to import a file from a path specified in a variable's value. For example, it looks like this: let test = require(configurationUrl); Here, configurationUrl represents a path such as '../../assets/app.conf.j ...

Encountering issues with running npm install on a local Angular project

Whenever I try to execute npm install on my local Angular project, I encounter the following errors: C:\Projects\Angular>npm install npm ERR! code ENOENT npm ERR! syscall spawn git npm ERR! path git npm ERR! errno ENOENT npm ERR! enoent Error ...

Choose a row by selecting the checkbox in the Kendo UI grid using TypeScript

I'm just starting out with Kendo UI and Angular 2, and I'm currently working on integrating Kendo UI with Angular 2. Specifically, I have a Grid Module set up with checkboxes in each row. My goal is to extract the row ID or any other field value ...

Facing issues while trying to deploy my Angular 5 application on Heroku

I've encountered an issue while attempting to deploy my Angular 5 project on Heroku. While I've successfully deployed other projects before, this one seems to have a dependency problem that is hindering the process. Locally, running ng build pos ...

Can you provide guidance on how to communicate an event between a service and a component in Angular 2?

I'm currently working with angular2-modal to create a modal alert in my application. I am specifically trying to capture the confirm event that occurs when the modal is triggered. Does anyone know how I can achieve this? ...

Utilize Firestore for automatic saving of data from Angular Reactive Forms

In my Angular application, I am facing an issue where data entered in a form needs to be instantly saved and updated in a Firestore database. This is crucial because multiple users will be entering data simultaneously on the same form, real-time values are ...

Exploring Angular 4's capability: Incorporating data from Http Post Response into a .js file or highchart

I'm a beginner with Angular 4. I'm trying to create a dashboard that pulls data from an Http Post Response and I want to use this data to create a Chart (Highchart). I have successfully received the response in the console.log and formatted it i ...

What is the process for invoking a microservice (constructed in express js) from an angular application that is currently communicating with a sails js backend?

I had initially developed an application with Angular frontend and Sails JS backend. However, I recently separated some of the backend functions into a micro-service using Express. Now, I am looking for guidance on how to call these functions from my mai ...

Error with Angular 2 observables in TypeScript

When a user types a search string into an input field, I want to implement a debounce feature that waits for at least 300 milliseconds before making a request to the _heroService using HTTP. Only modified search values should be sent to the service (distin ...

Upon the initial loading of GoJS and Angular Links, nodes are not bypassed

Hey there, I'm currently working on a workflow editor and renderer using Angular and GoJS. Everything seems to be in order, except for this one pesky bug that's bothering me. When the page first loads, the links don't avoid nodes properly. H ...

Understanding vulnerabilities in Angular and implementing effective solutions to address them

click here to view the image Hello everyone, I encountered an error message while attempting to install Bootstrap in my project using the code npm install --saved bootstrap. Can anyone provide assistance in simpler terms? ...

Tips for iterating through an observable using the .subscribe method

I am currently working on a function that involves looping and using .subscribe to receive an array object each time, with the intention of later pushing this data into another array. The loop itself is functional; however, there is an issue with the resul ...

Uh-oh! An unexpected type error occurred. It seems that the property 'paginator' cannot be set

I am developing a responsive table using Angular Material. To guide me, I found this helpful example here. Here is the progress I have made so far: HTML <mat-form-field> <input matInput (keyup)="applyFilter($event.target.value)" placeholder ...