如何将图像在Angular 7中与形式构建器中的文本上传到nodejs



我想在Angular中制作一个博客组件,我想单击以单击文本(如字幕(上传图像。

我也使用了Form Builder,但没有起作用。

例如

profile.component.html

<form [formGroup]="profileEdit" (submit)="onEditSubmit(profileEdit)" enctype="multipart/form-data">
   <div class="form-group">
        <div class="image-upload">
             <label for="file-input">
                   <img src="../../../../assets/test.jpg" alt="Paris" style="width:20%;">
             </label>
            <input id="file-input" type="file" name="image" formControlName="image" #image (change)="onFileSelect($event)" multiple/>
        </div>
    </div>
    <div class="form-group">
         <label class="form-label" for="name">Your Name</label>
                <input type="text" class="form-control" formControlName="name" #name placeholder={{user.user.name}} tabindex="1" required>
     </div>
     <div class="text-center">
         <button type="submit" class="btn btn-start-order" [disabled]="profileEdit.pristine || profileEdit.invalid">Save</button>
      </div>
</form>

和profile.component.ts文件

export class ProfileComponent implements OnInit {
  private _profileData:any;
  public edit:boolean=false;
  public user:any;
  public editedProfile:any;

  profileEdit:FormGroup;
  constructor(private _fb:FormBuilder) { 
           this.createForm();
       }
  ngOnInit() {
        };
  };
  createForm(){
  this.profileEdit = this._fb.group({
   name: [null,Validators.required],   
   image:[""]
 });

}

  onEditSubmit(){
    const formData = new FormData();
    formData.append("image",this.profileEdit.get("image").value);
    formData.append("name",this.profileEdit.get("name").value);

//formData.append("user",JSON.stringify(user));
//console.log(formData);
/*this._profile.editProfile(formData).subscribe(data=>{
  this.editedProfile = data;
  if(this.editProfile){
  }else{
  }
});*/
console.log(this.profileEdit.value);
  }
  onFileSelect(event) {
     if (event.target.files.length > 0) {
     const file = event.target.files[0];
      this.profileEdit.get("image").setValue(file);
    }
   }
}

我想通过单个组件

将图像上传到nodejs

您可以通过FormData

将图像和文本从Angular App发送到Nodejs
<input type="file" (change)="fileProgress($event)">
<input type="text" #caption> //Enter your caption
<button (click)="fnPostImage(caption.value)">post image</button>

export class PostImage {
public fileData;
 constructor(private http: HttpClient) { }
 fileProgress(event) {
    this.fileData = event.target.files;
  }
 fnPostImage(caption) {
    const formData = new FormData();    
    for (var i = 0; i < this.fileData.length; i++) {
      formData.append("image", this.fileData[i], this.fileData[i].name); 
     } 
    formData.append("caption", caption);
    this.http.post('https://api_url', formData).subscribe( (response) => {
       console.log(response) 
    }) 
  }
}

相关内容

  • 没有找到相关文章

最新更新