【问题标题】:Unable to send an image file using angular无法使用角度发送图像文件
【发布时间】:2019-05-05 13:29:39
【问题描述】:

我正在尝试将图像文件上传到表单中。

我尝试使用模板驱动的表单以及响应式表单。 使用响应式表单时,我使用 ViewChild 修补了文件的值(并且还尝试了从 filereader 中)。 我在服务函数发送 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){名称:“R-9347777-1479030303-3425.jpeg.jpg”,最后修改: 1543580533302,最后修改日期:2018 年 11 月 30 日星期五 17:52:13 GMT+0530 (印度标准时间),webkitRelativePath: "", size: 9208, ...}

这是服务中接收到的数据,接收到文件对象

收到的数据{文件:文件(9208),标题:“swagat”,备用标题: "patra",流派:"anime",类型:"movie",...}

错误

POST http://.../api/createAnime 500(内部服务器错误)

【问题讨论】:

    标签: angular image upload http-post


    【解决方案1】:

    将您的标题选项用作...

    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);
    

    我希望这会有所帮助

    【讨论】:

    • 好的,我将使用 formdata。但是为什么发布请求不起作用,即使数据已成功传递。我做错了什么吗?图片文件上传不能使用普通的http post请求吗?另一件事邮递员如何成功完成请求?有什么与涉及的相对路径相关的吗?因为我在邮递员中看到了请求有效负载,并找到了包含路径的文件对象,该路径是相对路径。
    • 我认为邮递员直接从相对路径获取文件对象,因此您可以直接传递文件对象而无需转换为formdata
    • 我使用了 viewchild 并在记录数据时发现文件对象在那里。那么发布请求是否会以某种方式更改文件对象?
    • 您是否尝试在 API 中传递该对象,我希望您在这里获得文件对象
    • 是的,我已经传递了文件对象,但请求总是返回错误 500
    【解决方案2】:

    方法一: 如果您使用POST方法和Content-type发送图像:JSON意味着图像内容转换为base64格式并将图像字符串内容发送到json对象变量。

    方法的缺点: 1. post 方法的 JSON 字符串大小取决于你的服务器。正常情况下,您可以发送小于 2MB 的图像。

    方法二: 使用FormData()将文件输入内容发送到服务器

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-30
      • 1970-01-01
      • 1970-01-01
      • 2020-05-17
      • 2019-11-22
      • 2020-08-01
      • 2015-04-04
      相关资源
      最近更新 更多