0

im working on a angular php project and im working on admin view where he will be able to add image of the project and i want to save the url in the database so i can show it in the client side how can i do that ?

this is my html code snippet for the image

<div class="row">
                    <div class="col-md-6 div">Image <span style="color:red;">* </span> </div>
                    <div class="col-md-6">
                        <input id="imageInput" type="file" class="form-control" formControlName="image_url"
                            name="image_url" accept="image/*" required="" (change)="setPhoto($event)">
                    </div>
                </div>

and this is my ts file

import { ElementRef, OnInit, ViewChild } from '@angular/core';
import { Component } from '@angular/core';
import { ApiService } from '../service/api.service';
import { Router } from '@angular/router';
import { FormArray, FormBuilder, FormControl, Validators, AbstractControl, ValidationErrors } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';
import { countries } from '../countries_data';

import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'app-addprojects',
  templateUrl: './addprojects.component.html',
  styleUrls: ['./addprojects.component.css']
})

export class AddprojectsComponent implements OnInit {
  addForm: any;
  projectCategories: any[] | undefined;

  imageUrl = null;
  photo?: Blob;


  public countries: any = countries
  selectedFile: any;
  constructor(
    private formbuilder: FormBuilder,
    private router: Router,
    private projectservice: ApiService,
    private toastr: ToastrService
  ) {
    this.addForm = this.formbuilder.group({
      // project_id: ['', [Validators.required, Validators.min(1), Validators.pattern("^[0-9]+$")]],
      title: ['', [Validators.required, Validators.maxLength(255), Validators.pattern("^[a-zA-Z]+$")]],
      description: ['', [Validators.required, Validators.maxLength(255), Validators.pattern("^[a-zA-Z]+$")]],
      start_date: ['', [Validators.required]],
      end_date: ['', [Validators.required]],
      code_cat: ['', [Validators.required, Validators.min(1), Validators.pattern("^[0-9]+$")]],
      project_country: ['', [Validators.required,]],
      project_holder: ['', Validators.required],
      image_url: ['', Validators.required]

    },
      { validator: this.endDateValidator }

    )
  }
  endDateValidator(group: AbstractControl): ValidationErrors | null {
    const startDate = group.get('start_date')?.value;
    const endDate = group.get('end_date')?.value;

    if (startDate && endDate && startDate > endDate) {

      return { endDateInvalid: true };
    }
    return null;
  }

  setPhoto(event: any) {
    if (event.target.files && event.target.files.length > 0) {
      this.photo = event.target.files[0];
    }
  }
  onSubmit() {
    if (this.addForm.valid && this.photo) {

      const formData = new FormData();
      formData.append('image_url', this.photo);
      console.log(formData)

      this.projectservice.createProjects(this.addForm.value).subscribe({
        next: (data: any) => {
          this.toastr.success('Project created successfully', 'Success');
          setTimeout(() => {
            this.router.navigate(['/view']);
          }, 1500);


        },
        error: (error: any) => {
          console.log(error);
          this.toastr.error('Project ID exists already', 'Error');
        }
      });
    }
    else {
      this.toastr.error('Please Fill the form correctly ', 'Error');
    }
  }


  get id() {
    return this.addForm.get('project_id')
  }

  ngOnInit() {
    this.projectservice.getCategory().subscribe(
      (result: any) => {
        this.projectCategories = result.data;
        console.log(this.projectCategories);
      },
      error => {
        // Handle error
      }
    );


  }


}

and this is my service

 createProjects(project: FormData) {

let headers = new HttpHeaders({
  'Content-Type': 'application/json'
});
// let data = JSON.stringify(project);
// console.log(project)
console.log(project)
return this.http.post(this.baseUrl + 'addproject.php', project, { headers });

}

im just now trying to get the image in the formdata and it gives me null everytime in the console.log

enter image description here

  • I don't see any nulls in that console output? Which bit are you saying is null? Always be specific, please. – ADyson May 23 '23 at 09:50
  • FormData is not getinng the image – Oussema Sahbeni May 23 '23 at 09:52
  • Which part are you struggling with? Uploading the data in Angular? Retrieving the upload in PHP? Writing data to the database? Reading data from the database? Piping that data from PHP to Angular? If you are facing any error message, add it to your post **in text form**, not hidden in a screenshot – Nico Haase May 23 '23 at 09:52
  • the other data uploads correctly the title etc etc , i want to upload the image url from the angular in my mysql using php , i want to save the image url in the mysql and save the image in the htdocs file of php so i can reuse it later in the client side – Oussema Sahbeni May 23 '23 at 09:55
  • `FormData is not getinng the image`...how do you know? You haven't even expanded the object in the console. Even that may not tell you precisely what's in it. See https://stackoverflow.com/a/17067016/5947043 for a better way to inspect what's actually in the FormData. – ADyson May 23 '23 at 09:56
  • Please add all clarification to your question by editing it. If you are already facing problems in the browser (such that you can't even send the data properly to the backend), please remove the tags for PHP and MySQL, as these techniques are not related. If I understood that wrong, please clarify your problem – Nico Haase May 23 '23 at 09:58
  • sorry im still new to angular, i think the right question is how to know if i uploded the the image correctly or no , i thought making console.log(formData) will show me if i uploded the image or no – Oussema Sahbeni May 23 '23 at 10:01
  • If you log the formData, it tells you what is in the formData object. It doesn't tell you what happens after that. If you want to know what was actually uploaded, go to the Network tab (instead of Console), find the relevant request, click on it, and go to the payload area. (Note that some browsers are not good at showing you this info when it comes to file uploads. Firefox usually does the best job, in my experience). – ADyson May 23 '23 at 22:41

0 Answers0