how to send file to php use HttpClient and FormData in ionic and how to Recepion file in php


I have input file in mypage.html on ionic and i want send this file to php because upload file on server
this, I create input text for the name file and input file to uploaded

    <ion-title>Send Data</ion-title>


<ion-card class="ion-align-items-center">
    <ion-card-subtitle>Send Data</ion-card-subtitle>
    <input type="text" [(ngModel)]="name1">
    <input type="file" [(ngModel)]="fle1" (change)="selectedFile($event)">
    <button (click)="OnClick()">Send</button>

this Code, i use HttpClient to send data and use FormData And converted to json Then sended to ‘http://localhost:8080/ionic/api.php’

import { Component, Input, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

  selector: 'app-login',
  templateUrl: './',
  styleUrls: ['./'],
export class LoginPage implements OnInit {

  constructor(private http: HttpClient) { }

    const formdata=new FormData();

this code app.module.ts i include HttpClientModule in page

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { HttpClientModule } from '@angular/common/http';
import { ReactiveFormsModule } from '@angular/forms';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

  declarations: [AppComponent],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule,HttpClientModule,ReactiveFormsModule],
  providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }],
  bootstrap: [AppComponent],
export class AppModule {}

and this code php ,I want received data I Don’t Now how to get temp file for uploaded

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

$json    = json_decode(file_get_contents('php://input'));
    $data = ['form'=>$json];
        echo json_encode($data);

I want help for this problem


one way would be to handle it as a blob

  selectedFile(event): void {
        if ( && {
          let file =[0];
          this.yourFormData = new FormData();
          let blob = new Blob([file], {
            type: 'application/octet-stream',
          this.yourFormData.append('file', blob);


Answered By – Niran Manandhar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published