首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用角度8上传图像

如何使用角度8上传图像
EN

Stack Overflow用户
提问于 2020-04-15 17:45:55
回答 1查看 990关注 0票数 0

app.module.ts

代码语言:javascript
复制
 ngOnInit() {
this.userForm = this.fb.group({
  firstName : ['', Validators.required],
  gender : ['', Validators.required],
  maritalStatus : ['', Validators.required],
  lastName : ['', Validators.required],
  dob : ['', Validators.required],
  nationality : ['', Validators.required],
  pic : [''],
  streetAddress : ['', Validators.required],
  city : ['', Validators.required],
  postalCode : ['', Validators.required],
  phone : ['', Validators.required],
  state : ['', Validators.required],
  country : ['', Validators.required],
  email : ['', Validators.required],
  jobTitle : ['', Validators.required],
  dateOfJoining : ['', Validators.required],
  department : ['', Validators.required],
  employeeStatus : ['', Validators.required],
  kra : ['', Validators.required],
  assignedSupervisor : ['', Validators.required],
  assignedSubordinate : ['', Validators.required],
  workExperience : ['', Validators.required],
  skills : ['', Validators.required],
  education : ['', Validators.required],
  password : ['', Validators.required]
})
}

onSubmit() {
this.submitted = true;
this.userService.addUser(this.userForm.value).subscribe(
  res => {
    this.model = res
    console.log(res)
  },
  error => {
    this.error = error,
    console.log(error)
  }
)

app.component.html

代码语言:javascript
复制
<div class="col-lg-12 col-12 mt-2">
 <label for="pic">Profile Picture</label><br/>
 <input type="file" formControlname='pic' name='pic'/>
</div>

app.service.ts

代码语言:javascript
复制
addUser(formData: User) {
return this.http.post<User>(`${this.serverUrl}`, formData).pipe(
  catchError(this.handleError)
);

}

每件事都很好。我只想知道如何上传图片的角度8。pic是上传在后端使用节点测试邮递员。有谁能帮我用角上传图片吗,请帮我

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-15 17:54:14

在发出post请求之前,请将formData转换为实际的FormData,如下所述:https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData

使用

代码语言:javascript
复制
addUser(formData: User) {
  const body = new FormData();
  for(const [key, value] of Object.entries(formData)){
     if(key === 'pic'){
        body.append(key, value)
     }
     body.append(key, `${value}`)
  }
  return this.http.post<User>(`${this.serverUrl}`, body).pipe(catchError(this.handleError);
);

那么后端应该会识别该文件。不幸的是,FormData期望stringblob作为值的数据类型。

虽然有人说:

如果发送的值与String或Blob不同,它将自动转换为String:(.)

我的编辑器(vs代码)告诉我不要使用数字,而是先转换它。

解决方案是假设User中其他属性的数据类型是原语。

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

https://stackoverflow.com/questions/61235210

复制
相关文章

相似问题

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