Search code examples
phpangularionic-frameworkng2-file-upload

how to submit input data along with ng2 file upload angular ionic


Please I want to send some text data with file upload(ng2 file upload) in angular ionic. I am new to angular and ionic as well. I have tried so many options but I don't seem to get a way out. I am using Php as a backend.I am able to send the file only but not the input data like username. Meanwhile I am able to log the input data that's username on the console but the server response is null. And it never inserts in my database. This is my code.

public fileUploader: FileUploader = new FileUploader({});

ngOnInit() {
    this.fileUploader = new FileUploader({ url: "http://localhost/paat/server/post.php"});
 
    this.fileUploader.onBuildItemForm = (fileItem: any, form: FormData): any => {
        form.append('body', this.body);
        form.append('username', this.username);

        // Add file to upload
        form.append('file', fileItem);

        fileItem.withCredentials = false;
        return { fileItem, form };
    };
}

fileOverBase(event): void {
    this.hasBaseDropZoneOver = event;
}

//return files from ng2 upload 
getFiles(): FileLikeObject[] {
    return this.fileUploader.queue.map((fileItem) => {
      return fileItem.file;
    });
}

// the upload method where the post to server is made
uploadFiles() {
    let bodys = {
      body:this.body,
      username:this.username,
    };
    let files = this.getFiles();
    let requests = [];
    
    files.forEach((file) => {
        let formData = new FormData();
        formData.append('file' , file.rawFile, file.name);
        formData.append('body' , this.body);
        formData.append('username' , this.username);
        requests.push(this.uploadingService.uploadFormData(formData));
    });

    concat(...requests).subscribe(
        (res) => {
            console.log(res);
            console.log(this.body);
            console.log(this.username);
            console.log(this.file.name);
        },
        (err) => {  
            console.log(err);
        }
    );
}

this is my uploadservice.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
    providedIn: 'root'
})
export class UploadingService {

  API_SERVER: string = "http://localhost/paat/server/post.php";
  
  constructor(private http: HttpClient) { }

    public uploadFormData(formData) {
        return this.http.post<any>(`${this.API_SERVER}`, formData);
    }
}

This is my backend code:

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods:POST,GET,PUT,DELETE");
header("Access-Control-Max-Age:86400");
header("Access-Control-Allow-Headers: Content-Type,Access-Control-Allow-Headers,Authorization,X-Requested-With");

$con = mysqli_connect("localhost", "root", "", "social");
$postjson = json_decode(file_get_contents('php://input'), true);

$filename = $_FILES['file']['name'];
$meta = $_POST;
$targetDir = "assets/images/posts/";
$destination = $targetDir . $filename;
move_uploaded_file( $_FILES['file']['tmp_name'] , $destination );

$body = $postjson['body'];
  
$date_added = date("Y-m-d H:i:s");

//get username
$added_by = $postjson['username'];

//if user is on own profile, user_to is 'none'
$targetfile = $destination;
    
$user_to ="none";

$query = mysqli_query($con,"INSERT INTO posts VALUES(NULL, '$body', '$added_by', '$user_to', '$date_added', 'no', 'no', '0', '$targetfile')");

What am I doing wrong? Please help.


Solution

  • I have found out what I was doing wrong. The problem was with my backend code. It was the way I was retrieving the formdata values from the request. So I changed

    $body = $postjson['body'];
    $added_by = $postjson['username'];
    
    

    to

    $body = $_POST['body'];
    $added_by = $_POST['username'];
    
    

    Also I modified my ngOnInit() method and the instance of fileuploader method to

    public fileUploader: FileUploader = new FileUploader({ url: "http://localhost/paat/server/post.php"});
    
    ngOnInit() {
       
        
        this.fileUploader.onBuildItemForm = (fileItem: any, form: FormData): any => {
          
          form.append('body', this.body);
    
          // Add file to upload
          form.append('file', fileItem);
          form.append('username', this.username);
    
        
          fileItem.withCredentials = false;
          return { fileItem, form };
        };
    }
    
    

    and it now works.