简体   繁体   中英

How can I upload form data and image file to PhpMyAdmin table in angular?

I have just now started angular so I did whatever I am familiar with. I created a component and a service to upload the form data but I am not able to write the.php and I don't know if I have written the correct code. Please help me if I have missed something

I expected this details to be added in phpmyadmin table "books" with the following columns - bname, bpic, bauthor, bgenre, bsummary

apublish.component.html


<div class="container-fluid">
<div class="row">
   <div class="md-col-12 text-center bg-warning">
     <h1>Image </h1>
    </div>
</div>
<div class="container">
    
   <form [formGroup]="form" (ngSubmit)="onSubmit()">
        <div class="form-group input-group-lg">
            <input class="form-control" placeholder="Book name" formController="bname">
        </div>
        <div class="form-group">
            <input type="file" (change)="uploadFile($event)">
        </div>
        <div class="form-group input-group-lg">
            <input class="form-control" placeholder="Book author" formController="bauthor">
        </div>
        <div class="form-group input-group-lg">
            <input class="form-control" placeholder="Book name" formController="bgenre">
        </div>
        <div class="form-group input-group-lg">
            <input class="form-control" placeholder="Book name" formController="bsummary">
        </div>
        <div class="form-group">
            <button class="btn btn-success btn-block btn-lg btn-block">Submit</button>
        </div>
   </form>

</div>

apublish.component.ts

import { HttpEvent, HttpEventType, HttpResponse } from '@angular/common/http';
import { Component } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { ImageUploadService } from './image-upload.service';

@Component({
  selector: 'app-apublish',
  templateUrl: './apublish.component.html',
  styleUrls: ['./apublish.component.css']
})
export class ApublishComponent {
  title="ngFileUpload";
  form:FormGroup;
  progress:number=0;
  msgs: any;
  imgMsg: any;
 
  constructor(public fb: FormBuilder, public imageUploadService: ImageUploadService){
    this.form=this.fb.group({
      bname:[''],
      bpic:[null],
      bauthor:[''],
      bgenre:[''],
      bsummary:['']
    })
  }

  uploadFile(event:any){
    const file=event.target.files ? event.target.files[0] :'';
    //console.log(file);
    this.form.patchValue({
      image:file
    });
    this.form.get('bpic')?.updateValueAndValidity()
  }

  submitImage(){
    this.imageUploadService.imageUpload(
      this.form.value.bname,
      this.form.value.bpic,
      this.form.value.bauthor,
      this.form.value.bgenre,
      this.form.value.bsummary
    ).subscribe((event:HttpEvent<any>)=>{
      switch (event.type){
        case HttpEventType.UploadProgress:
          if(event.total){
            this.progress=Math.round((100/event.total)*event.loaded);
            this.msgs="Uploaded! $(this.progress)%";
          }
          break;
        case HttpEventType.Response:
          event.body;
          
          if(event.body.success){
            this.imgMsg=event.body.error
          }
          else if(event.body.success){
            this.imgMsg=event.body.success
          }
          setTimeout(()=>{
          this.progress=0;
          this.msgs='';
        },1500);
      }
    })

  }
}

image-upload.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { catchError, Observable, throwError } from 'rxjs';
@Injectable({
  providedIn: 'root'
})
export class ImageUploadService {

  constructor(private http:HttpClient) { }

  imageUpload(bname :string,
    bpic:File,
    bauthor:string,
    bgenre:string,
    bsummary:string):Observable<any>{
      var formData:any=new FormData();
      formData.append("bname", bname);
      formData.append("filetoUpload", bpic);
      formData.append("bauthor", bauthor);
      formData.append("bgenre", bgenre);
      formData.append("bsummary", bsummary);
      return this.http.post('http://localhost/testang/php/single-upload.php', 
      formData,{
        reportProgress:true,
        observe:'events'
      }).pipe(
        catchError((err:any)=>{
          alert(err.message);
          return throwError(err.message);
        })
      )
    }
   
}

Here's how you could solve the problem:

  • Learn about how to work with form in Angular. Currently, you're using Reactive Form. So make sure you know how to work with it .
    The reason? Well, there's no such thing as formController in Reactive Form
  • Use console.log to check the form value, is the form empty? is it valid? is the form's value follow the expected format...
    The reason? You first need to make sure you're sending the correct value to your server
  • Use DevTool's.network tab to see if you're sending to the correct endpoint/api.
    The reason: aside from correct endpoint, you will also know what's the response, whether it's 200 or 4xx or 5xx. This is important detail to debug

Last but not least. Just make sure you show what's the current issue is. Don't just say it doesn't work , if it doesn't work then what's the error message? Did you follow the error message to resolve the issue? If you did follow the message, what have you found/tried?

PS: you're working with Angular, NOT angularjs, so don't make a tag with angularjs.

Happy coding!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM