photo-form.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { PhotoService } from '../photo/photo.service';
import { Router } from '@angular/router';
@Component({
selector: 'ap-photo-form',
templateUrl: './photo-form.component.html',
styleUrls: ['./photo-form.component.css']
})
export class PhotoFormComponent implements OnInit {
photoForm: FormGroup;
file: File;
constructor(
private formBuilder: FormBuilder,
private photoService: PhotoService,
private router: Router
) { }
ngOnInit() {
this.photoForm = this.formBuilder.group({
file: ['', Validators.required],
description: ['', Validators.maxLength(300)],
allowComments: [true]
})
}
upload(){
const description = this.photoForm.get('description').value;
const allowComments = this.photoForm.get('allowComments').value;
console.log(this.file);
this.photoService
.upload(description, allowComments, this.file)
.subscribe(() => this.router.navigate(['']))
}
}
photo.service.ts
upload(description: string, allowComments: boolean, file: File){
// I'm not sending a JSON, must send FormData
const formData = new FormData();
formData.append('description', description);
formData.append('allowComments', allowComments ? 'true' : 'false');
formData.append('imageFile', file);
return this.http.post(API + '/photos/upload', formData);
}
this.file & erro:
File {name: "HCP_Logo_New_PsychK-197x300.jpg", lastModified: 1574785757925, lastModifiedDate: Tue Nov 26 2019 13:29:17 GMT-0300 (Horário Padrão de Brasília), webkitRelativePath: "", size: 35243, …}
name: "HCP_Logo_New_PsychK-197x300.jpg"
lastModified: 1574785757925
lastModifiedDate: Tue Nov 26 2019 13:29:17 GMT-0300 (Horário Padrão de Brasília) {}
webkitRelativePath: ""
size: 35243
type: "image/jpeg"
__proto__: File
POST http://localhost:3000/photos/upload 500 (Internal Server Error)
ERROR HttpErrorResponse {headers: HttpHeaders, status: 500, statusText: "Internal Server Error", url: "http://localhost:3000/photos/upload", ok: false, …}