Невозможно отправить файл изображения, используя угловой - PullRequest
0 голосов
/ 04 декабря 2018

Я пытаюсь загрузить файл изображения в форму.

Я пытался использовать формы на основе шаблонов, а также реактивные формы.При использовании реактивных форм я пропатчил значение файла с помощью ViewChild (а также попытался из программы чтения файлов).Я зарегистрировал данные, переданные службе, до того, как функция службы отправила http-запрос.

Проблема в том, что зарегистрированные данные в порядке;объект файла изображения и другие пары ключ-значение, но когда запрос http post выполнен, ответом является ошибка 500. Я даже проверил с помощью почтальона, но получил ответ 200.

здесь 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() }));
    }
  }

И, наконец, журналы

// fileToUpload, которые исправлены в registerForm

Файл (9208) {name: "R-9347777-1479030303-3425.jpeg.jpg ", lastModified: 1543580533302, lastModifiedDate: пт 30 ноября 2018 17:52:13 GMT + 0530 (стандартное время Индии), webkitRelativePath:" ", размер: 9208,…}

этоэто данные, полученные в сервисе, объект файла получен

данные получены {файл: файл (9208), заголовок: "swagat", альтернативный заголовок: "patra", жанры: "аниме", тип:"movie",…}

ошибка

POST http: //.../api/createAnime 500 (Внутренняя ошибка сервера)

Ответы [ 2 ]

0 голосов
/ 04 декабря 2018

Используйте опцию заголовка как ...

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

и создайте formdata и используйте в своем методе POST как data

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

Я надеюсь, что это поможет

0 голосов
/ 04 декабря 2018

Метод 1: Если вы отправляете изображение с использованием метода POST и Content-type: JSON означает, что содержимое изображения преобразуется в формат base64 и отправляет содержимое строки изображения в переменную объекта json.

Недостаток метода: 1. Размер строки JSON метода post в зависимости от вашего сервера.В обычном случае вы можете отправлять изображения размером до 2 МБ.

Способ 2: Использование FormData () для отправки входного содержимого файла на сервер

...