1

I am trying to upload an image file into a form.

I tried using template driven forms as well as reactive forms. When using reactive forms, i patched the value of file using ViewChild(and also tried from filereader). I logged the data passed to the service before the service function was sending http request.

The problem is the logged data is fine; an image file object and other key and value pairs, but when the http post request is done, the response is error 500. I even checked using postman but got the response 200.

here is the ts

        import { Component, OnInit } from '@angular/core';
        import { UsersdataService } from './../../service/usersdata.service';
        import { FormControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
        import { ViewChild, ElementRef } from '@angular/core';
        import { HttpClientModule } from '@angular/common/http';


        @Component({
          templateUrl: './amine.component.html',
          selector: 'amine',
          styleUrls: ['./amine.component.scss']
        })
        export class AmineComponent implements OnInit {

          constructor(public userServ: UsersdataService, public formBuilder: FormBuilder, httpClient: HttpClientModule) { }//use public

        public values;
          public token = localStorage.getItem('currentUser');
          registerForm: FormGroup;
          public input;
          public fileToUpload;


          @ViewChild('fileInput') fileInput: ElementRef;

        ngOnInit() {
            console.log(`the token is ${this.token}`);
            console.log('anime ');
            this.userServ.getAllAnime1().subscribe((data1) => { 
              console.log((data1.json()));
              console.log(`data 12 is ${data1}`)
              this.values = data1.json().data;
              console.log(this.values);
              /*for(let x of this.values){
                console.log(x)
              }*/
            },
              (err) => {
                console.log(`error is ${err}`)
              })


            ///////////////////////////////////////////implementation of reactive-forms inside ngOnInit
            this.registerForm = new FormGroup({
              //password: new FormControl(''),//['', [Validators.required, Validators.minLength(6)]],
              file: new FormControl(''),
              //"http://103.14.127.78:3008/file-1543814902119.jpeg"),//['',Validators.required]
              title: new FormControl(''),
              alternatetitle: new FormControl(''),
              genres: new FormControl(''),
              type: new FormControl(''),
              release: new FormControl(''),
              externalurl: new FormControl(''),
              description: new FormControl(''),
              rating: new FormControl(''),
              studio: new FormControl(''),
              status: new FormControl(''),
              duration: new FormControl(''),

            });

          }



          /////////////////////////////////////////////////reactive form code

          public image: any;
          //onFileChange(event) {
            //console.log("file input ref value" + fileInputRef.value);
            //let file1 = this.fileInputRef;
            //console.log("file input ref value"+Object.entries(file1));
            //let reader = new FileReader();

            //this.image = event.target.files[0];
            //const [file] = event.target.files;
            //reader.readAsDataURL(file);

            //reader.onload = () => {
            //  this.registerForm.patchValue({
            //    file: reader.result
            //  });
            //  console.log(reader.result);


            //}
            //this.formData.append("file", event.target.files[0]);
          }
          addFileViewChild(): void {
            let fi = this.fileInput.nativeElement;//fileInput is the temp ref var

            this.fileToUpload = fi.files[0];
            console.log(this.fileToUpload);    
          }

          onSubmitAngularForm() {

            // this.input = this.registerForm.value;
            // console.log(this.input);
            //console.log(this.fileToUpload);
            this.registerForm.patchValue({
              title: 'swagat',
              alternatetitle: 'patra',
              genres: 'anime',
              type: 'movie',
              release: '12',
              externalurl: 'http://movie.com',
              description: '123',
              rating: '9',
              studio: 'wal',
              status: 'watched',
              duration: '12',
              //file: this.registerForm.patchValue({
              file: this.fileToUpload//"http://103.14.127.78:3008/file-1543814902119.jpeg"
              //file:this.image
            });
            // console.warn(this.registerForm);
            // console.warn(this.registerForm.value);
            console.log("file data submit ", { ...this.registerForm.value, file: this.image });
            this.userServ.createAnime({ ...this.registerForm.value, file: this.image }).subscribe(
              res => console.log(res),
              err => console.log(JSON.stringify(err))
            )
          }

        and here is the html

    <head>

        <title>Document</title>
    </head>

    <body>

        <!-- top line pink color -->
        <div class="top-line"></div>
        <!-- top line pink color -->


    <form [formGroup]="registerForm" (ngSubmit)="onSubmitAngularForm()">
    <label>
                                                    file
                                                    <input type="file" (change)="addFileViewChild()"  #fileInput >
                                                </label>

                                                <label>
                                                    Title
                                                    <input type="text" formControlName="title">
                                                </label>

                                                <label>
                                                    Alternate Title
                                                    <input type="text" formControlName="alternatetitle">
                                                </label>

                                                <label>
                                                    genres
                                                    <input type="text" formControlName="genres">
                                                </label>

                                                <label>
                                                    type
                                                    <input type="text" formControlName="type">
                                                </label>

                                                <label>
                                                    Release
                                                    <input type="text" formControlName="release">
                                                </label>
                                                <label>
                                                    external url
                                                    <input type="text" formControlName="externalurl">
                                                </label>
                                                <label>
                                                    description
                                                    <input type="text" formControlName="description">
                                                </label>
                                                <label>
                                                    rating
                                                    <input type="text" formControlName="rating">
                                                </label>
                                                <label>
                                                    studio
                                                    <input type="text" formControlName="studio">
                                                </label>
                                                <label>
                                                    duration
                                                    <input type="text" formControlName="duration">
                                                </label>
                                                <button type="submit" >Submit</button>
                                            </form>
                                                 </div>

    </body>


and here is the service.ts

import { Injectable } from "@angular/core";
import { Response, Headers, Http } from "@angular/http";
import { HttpClientModule } from "@angular/common/http";
import { Observable } from "rxjs";
import * as globalVariable from "../global";
import "rxjs/add/operator/map";
import { catchError, map } from "rxjs/operators";


@Injectable()
export class UsersdataService {

  private header: Headers = new Headers();

  public token = localStorage.getItem('currentUser');

  public httpOptions = {
    headers: new Headers({
      "Content-Type": "application/json",
      "x-auth": this.token//JSON.parse(localStorage.getItem("currentUser")),

    })
  };

constructor(private http: Http) { }

  getAllAnime() {
    return this.http.get(globalVariable.url + "api/getAllAnime")
      .map((response: Response) => response.json())
  }

  getAllAnime1() {
    console.log('user service called');
    return this.http.get(globalVariable.url + "api/getAllAnime");
  }

createAnime(data) {
console.log("data received ", data);
    return this.http.post(globalVariable.url + "api/createAnime", data, this.httpOptions).pipe(map(res => { return res.json() }));
    }
  }

And finally the logs

//fileToUpload which is patched to the registerForm

File(9208) {name: "R-9347777-1479030303-3425.jpeg.jpg", lastModified: 1543580533302, lastModifiedDate: Fri Nov 30 2018 17:52:13 GMT+0530 (India Standard Time), webkitRelativePath: "", size: 9208, …}

this is the data received in service, file object is received

data received {file: File(9208), title: "swagat", alternatetitle: "patra", genres: "anime", type: "movie", …}

the error

POST http://.../api/createAnime 500 (Internal Server Error)

2 Answers 2

1

Use your header option as...

public httpOptions = {
 headers: new Headers({
   "Content-Type": "multipart/form-data",
   "x-auth": this.token//JSON.parse(localStorage.getItem("currentUser"))
 })
};

and create formdata and use in your POST method as data

const formdata: FormData = new FormData();
formdata.append('uploadedFile', this.currentFileUpload);

i hope this will help

Sign up to request clarification or add additional context in comments.

6 Comments

ok i will use formdata. but why is the post request not working, even though the data is passed susccessfuly. is there anything i am doing wrong? can a normal http post request not be used for image file upload? another thing how is postman successfully doing the request? is there anything related to relative pathing involved? because i saw the request payload in postman and found the file object containing a path which was the relative path.
i think postman directly getting file object from relative path so you can just pass file object directly without converting into formdata
i have used viewchild and on logging data i found the file object to be there. so is the post request changing the file object somehow?
did you try to pass that object in API, i hope here you get file object
yes i have passed the file object but the request always returns error 500
|
0

Method 1: If You send the image using POST method and Content-type: JSON means the image content converts to base64 format and send image string content to json object variable.

The drawback on method: 1. The post method JSON string size based on your server. The normal case you can send Below 2MB of images.

Method 2: Using FormData() to send file input content to the server

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.