首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法使用角发送图像文件

无法使用角发送图像文件
EN

Stack Overflow用户
提问于 2018-12-04 07:15:18
回答 2查看 1.3K关注 0票数 1

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

我尝试使用模板驱动的表单以及反应性表单。在使用反应性表单时,我使用ViewChild修补了文件的值(也尝试使用filereader)。在服务函数发送http请求之前,我记录了传递给服务的数据。

问题是记录的数据很好;图像文件对象和其他键和值对,但是当完成http请求时,响应是错误500。我甚至用邮递员查过了,但得到了200的回复。

这里是ts

代码语言:javascript
复制
        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",lastModified: 1543580533302,lastModifiedDate: 2018年11月30日星期五17:52:13 GMT+0530 (印度标准时间),webkitRelativePath:"",大小: 9208,…}

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

接收到的数据{file: File(9208),标题:"swagat",备选标题:"patra",体裁:“动画”,类型:“电影”,…}

误差

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

EN

回答 2

Stack Overflow用户

发布于 2018-12-04 08:10:43

用你的标题选项作为..。

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

并创建formdata并在POST方法中用作data

代码语言:javascript
复制
const formdata: FormData = new FormData();
formdata.append('uploadedFile', this.currentFileUpload);

我希望这能帮上忙

票数 1
EN

Stack Overflow用户

发布于 2018-12-04 07:49:31

方法1:如果您使用POST方法和内容类型: JSON发送图像,则表示图像内容转换为base64格式,并将图像字符串内容发送给json对象变量。

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

方法2:使用FormData()向服务器发送文件输入内容的

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53607563

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档