我试图使用角反应式表单在服务器上上传文件。当我尝试编辑会生成错误内部服务器错误的表单,但是当我使用邮递员成功更新文件 我不知道我的 FormData放置请求中缺少什么?发布请求成功运行
addteacher.component.html
import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators ,FormGroup,FormArray,FormControl} from '@angular/forms'
import { TeacherServiceService } from '../shared/teacher/teacher-service.service';
import {ActivatedRoute,Router} from '@angular/router';
import {Teacher} from '../shared/teacher/teacher';
@Component({
selector: 'app-addteacher',
templateUrl: './addteacher.component.html',
styleUrls: ['./addteacher.component.css']
})
export class AddteacherComponent implements OnInit {
teacherform:FormGroup;
teacher: Teacher;
FormTitle:String;
constructor(private fb: FormBuilder,
private teacherService: TeacherServiceService,
private route : ActivatedRoute,
private router : Router
) { }
ngOnInit() {
this.teacherform = this.fb.group({
t_p_img: [''],
t_id: [''],
t_name: [''],
t_desig: [''],
t_dob: [''],
t_pswd: [''],
t_email: ['',[Validators.required]],
t_gender: [''],
t_phone: [''],
t_quali: [''],
t_address: ['']
});
//Getting Teacher id
this.route.paramMap.subscribe(params=>{
const techId = params.get('id');
if(techId){
this.FormTitle = "Update Teacher Form";
this.getTeacherr(techId);
}
else{
this.FormTitle = "Teacher Registration Form";
this.teacher = {
t_id:null,
t_name:'',
t_desig: '',
t_dob:null,
t_email:'',
t_pswd:'',
t_gender:'',
t_phone:null,
t_quali:'',
t_p_img:'',
t_address:'',
_id:null,
courses:[]
}
}
});
}//
selectedFile(event) {
if (event.target.files.length > 0) {
const file = event.target.files[0];
this.teacherform.get('t_p_img').setValue(file);
}
}
saveRecord():void {
var formData:any = new FormData();
var t_p_image = this.teacherform.value.t_p_img;
var t_email = this.teacherform.value.t_email;
var t_id = this.teacherform.value.t_id;
var t_name = this.teacherform.value.t_name;
var t_desig = this.teacherform.value.t_desig;
var t_dob = this.teacherform.value.t_dob;
var t_pswd = this.teacherform.value.t_pswd;
var t_gender = this.teacherform.value.t_gender;
var t_phone = this.teacherform.value.t_phone;
var t_quali = this.teacherform.value.t_quali;
var t_address= this.teacherform.value.t_address
formData.append('file',t_p_image) ;
formData.append('t_id',t_id) ;
formData.append('t_name',t_name);
formData.append('t_desig',t_desig);
formData.append('t_dob',t_dob);
formData.append('t_pswd',t_pswd);
formData.append('t_email',t_email);
formData.append('t_gender',t_gender);
formData.append('t_phone',t_phone);
formData.append('t_quali',t_quali);
formData.append('t_address',t_address);
// console.log(formData)
// this.MapFormValuesToTeacherModel();
if(this.teacher._id){
this.teacherService.updateTeacher(this.teacher._id,formData).subscribe(
()=>this.router.navigate(['teacher']),
(err:any)=>console.log(err)
);
}else{
this.teacherService.createTeacher(formData).subscribe(
()=>this.router.navigate(['teacher']),
(err:any)=>console.log(err)
);}
}
getTeacherr(techId:any){
this.teacherService.getTeacher(techId).subscribe(
(teacher:Teacher)=>{
this.editTeacher(teacher);
this.teacher = teacher
} ,
(err:any)=>{
console.log(err);
}
)
}
editTeacher(teacher:Teacher){
this.teacherform.patchValue({
t_p_img:teacher.t_p_img,
t_id: teacher.t_id,
t_name: teacher.t_name,
t_desig: teacher.t_desig,
t_dob: teacher.t_dob,
t_pswd: teacher.t_pswd,
t_email: teacher.t_email,
t_gender: teacher.t_gender,
t_phone: teacher.t_phone,
t_quali: teacher.t_quali,
t_address: teacher.t_address
});
}
}
这是TeacherServiceService
import { Injectable } from '@angular/core';
import {Teacher} from './teacher';
import {HttpClient,HttpHeaders} from '@angular/common/http';
import {Observable,throwError, from} from 'rxjs';
import {retry,catchError} from'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class TeacherServiceService {
// Headers
httpOptions={
headers: new HttpHeaders({
'content-type':'application/json'
})
}
//Api Address
apiUrl = 'http://localhost:3000';
constructor(private http:HttpClient) { }
// Requests
createTeacher(teacher:any) {
return this.http.post(this.apiUrl+'/teacher',teacher)
.pipe(
retry(2),
catchError(this.handleError)
)};
//Getting All the teacher
showTeachers(): Observable <Teacher[]> {
return this.http.get<Teacher[]>(this.apiUrl+'/teacher',)
.pipe(
retry(2),
catchError(this.handleError)
)
};
// get a Single Teacher
getTeacher(id:any): Observable <Teacher>{
return this.http.get<Teacher>(this.apiUrl + '/teacher/'+id, this.httpOptions)
.pipe(
retry(1),
catchError(this.handleError)
)};
// Updating Teacher
updateTeacher(id,formData:any) {
return this.http.put(this.apiUrl + '/teacher/'+id, formData)
.pipe(catchError(this.handleError));
};
答案 0 :(得分:0)
您正在尝试使用不正确的文件设置value属性,这将引发错误,
this.teacherform.get('t_p_img').setValue(file);
检查此解决方案
答案 1 :(得分:0)
好的,您可以这样做
第一
slectedFile: File;
//imgUrl for showing it in html tag
imgUrl = '../assets/img/profilepic.png';
第二:
form: FormGroup = this.fb.group({
//........
file: [null]
});
第三:
onFileSelect(file) {
if (file.target.files[0]) {
this.slectedFile = file.target.files[0] as File;
const reader = new FileReader();
reader.readAsDataURL(this.slectedFile);
reader.onload = (event: any) => {
this.imgUrl = event.target.result;
};
}
}
最后:
我认为您的主要问题在这里
const data= new FormData();
if (this.slectedFile) {
data.append('file', this.slectedFile, this.slectedFile.name);
}
我应该提到,个人使用此软件包进行输入
https://www.npmjs.com/package/ngx-material-file-input
在html方面,您只需说:
<mat-form-field class="col-md-12 ml-10 ngxmatfileinput">
<ngx-mat-file-input
(change)="onFileSelect($event)"
formControlName="file"
accept="image/*">
</ngx-mat-file-input>
<img [src]="imgUrl" class="float-left icon-fileupload" />
</mat-form-field>