Angular在图像上传失败

时间:2019-05-11 18:41:50

标签: node.js angular file-upload angular-validation

我有一个角度应用程序,我需要在其中将图像上传到服务器(节点后端)。我尝试了在Internet上找到的不同方法,但是所有这些方法都存在相同的问题:服务器未接收到图像。如果我使用纯HTML格式,则服务器可以正常工作,甚至将服务器库从multer更改为express-upload,但问题仍然存在,因此我很确定这是一个有角度的问题。

HTML

<form [formGroup]="imageForm" *ngIf="state == 2" (ngSubmit)="uploadImage()">
    <mat-form-field appearance="outline">
        <ngx-mat-file-input formControlName="image" placeholder="Imagen" accept="image/*"></ngx-mat-file-input>
        <mat-icon matSuffix color="primary">folder_open</mat-icon>
        <mat-error *ngIf="image.errors && (image.dirty || image.touched)">{{getImageMessage()}}</mat-error>
    </mat-form-field>
    <div>
        <button mat-stroked-button color="primary" (click)="closeModal()">Cancelar</button>
        <button mat-flat-button color="primary" [disabled]="image.errors" type="submit">Aceptar</button>
    </div>
</form>

TS(简体)

import { Component, OnInit } from '@angular/core';
import { MatDialogRef } from '@angular/material';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { FileValidator } from 'ngx-material-file-input';
import { HttpClient, HttpRequest, HttpEvent, HttpEventType, HttpHeaders } from '@angular/common/http';

import { WriteComponent } from './../../write/write.component';

import { RequestsService } from './../../services/requests.service';

@Component({
    selector: 'app-upload-image',
    templateUrl: './upload-image.component.html',
    styleUrls: ['./upload-image.component.scss']
})
export class UploadImageComponent implements OnInit {
    private uploadImageURL = '/ajax/upload/image/';
    private state = 0;

    private urlForm: FormGroup;
    private imageForm: FormGroup;

    private regexUrl = 'https?://.+';

    private image: FormControl = new FormControl('', [Validators.required, FileValidator.maxContentSize(5000000)]); // 5mb

    constructor(private dialogRef: MatDialogRef<WriteComponent>, private http: HttpClient) { }

    ngOnInit() {
        this.imageForm = new FormGroup({
            image: this.image
        });
    }

    private uploadImage() {
        const formData = new FormData();
        formData.append('image', this.imageForm.get('image').value);
        this.http.post(this.uploadImageURL, formData).subscribe(output => {
            console.log('File transfered');
        });
    }
}

Browser request 表单数据是图像:[对象对象],也许是问题所在?

在服务器中,我仍然需要未定义的req.files

3 个答案:

答案 0 :(得分:0)

有一些可能的解决方案来解决您的问题。

  1. 检查是否已将服务器的“内容类型”设置为接收多部分/表单数据
  2. 尝试在POST方法中在此处添加类型,例如<Label text="Price" /> <ObjectNumber number = "{path : 'model>Price', formatter : '.formatCurrency'}" />

    <any>

    重点是,删除 private 访问修饰符以使POST方法公开可用。

答案 1 :(得分:0)

如果将图像发送到服务器,则必须使用FormData

示例

const cardData = new FormData();
cardData.append('frontImage', this.frontImageFile, this.frontImageFile.name);
cardData.append('first_name', this.newCardForm.value.first_name);
cardData.append('email', this.newCardForm.value.email);

让我知道您是否仍然有任何问题

答案 2 :(得分:0)

好吧,几天后,我把它拿出来了。

通过模板为this.image分配值是错误的。我必须使用一个函数和一个新变量来执行此操作,然后在提交时将该值分配给“图像”字段:

HTML

    <ngx-mat-file-input formControlName="image" placeholder="Imagen" accept="image/*" (change)="onFileChange($event)"></ngx-mat-file-input>

Ts

private imgFile;

private uploadImage() {
    const formData = new FormData();
    formData.append('image', this.imgFile);
    this.req.uploadImage(formData).subscribe(output => {
        console.log(output);
    }, () => {
        console.log('Error');
    }, () => {
        console.log('Complete');
    });
}

private onFileChange(event) {
    if (event.target.files.length > 0) {
        const file = event.target.files[0];
        this.imgFile = file;
    } else {
        this.imgFile = null;
    }
}