Ionic image upload with PHP server - php

I have a problem with my ionic app.
I want to upload an image to my php server when i click on a button but it seems that i am doing something wrong...
Communication.html
<ion-header>
<ion-navbar>
<ion-title>
Ionic3 Server Send Test
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-list>
<ion-item>
<button ion-button (click)="uploadFile()">Upload</button>
</ion-item>
</ion-list>
</ion-content>
Communication.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { HttpClient } from '#angular/common/http';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '#ionic-native/file-transfer';
#Component({
selector: 'communication',
templateUrl: 'communication.html'
})
export class CommunicationPage {
imageURI:any;
imageFileName:any;
constructor(public navCtrl: NavController,
private transfer: FileTransfer) {}
uploadFile() {
const fileTransfer: FileTransferObject = this.transfer.create();
let options: FileUploadOptions = {
fileKey: 'ionicfile',
fileName: 'ionicfile',
chunkedMode: false,
headers: {}
}
fileTransfer.upload('C:/Users/Nathan/Desktop/Recognize/src/pages/communication/test.png', 'http://someserver', options)
.then((data) => {
console.log(data+" Uploaded Successfully");
}, (err) => {
console.log(err);
});
}
}
I have this error when i click on the upload button :
FileTransferError {code: 1, source:"C:/Users/Nathan/Desktop/Recognize/src/pages/communication/test.png", target: "http://someserver", http_status: null, body: null, …}
I know there is a problem with the url of the "test.png" file because of code 1 error.
Do you have any idea ?

You need to add image targetPath in fileTransfer.upload() like this,
var targetPath = this.file.dataDirectory + imgName;
fileTransfer.upload(targetPath, 'http://someserver', options)
.then((data) => {
console.log(data+" Uploaded Successfully");
}, (err) => {
console.log(err);
});

Hey Nathan the problem you are having is because of the URL of file, here you are giving the url only test.png.
Rather than you should use FileChooser plugin for cordova which gives the absolute URL of the file.
import { FileChooser } from '#ionic-native/file-chooser';
constructor(private fileChooser: FileChooser) { }
function() {
const fileTransfer: FileTransferObject = this.transfer.create();
let options: FileUploadOptions = {
fileKey: 'ionicfile',
fileName: 'ionicfile',
chunkedMode: false,
headers: {}
}
this.fileChooser.open()
.then(uri => {
fileTransfer.upload(uri, 'http://someserver', options)
.then((data) => {
console.log(data+" Uploaded Successfully");
}, (err) => {
console.log(err);
});
})
.catch(e => console.log(e));
}
Comment down if you want some more help.

Related

php cannot read FormData that contains multiple files

In php, I cannot access the uploaded files in $_FILES instead they appear in $_POST["imgs"] as [object File] without any properties like name.
How can I get those files accessed in $_FILES?
import React, { useCallback } from 'react'
import { useDropzone } from 'react-dropzone'
import axios from 'axios'
const imgAjaxUploader = axios.create({
baseURL: 'http://localhost',
timeout: 1000,
headers: { 'Content-Type': 'mulipart/form-data' }
});
export default function ImgDropzone() {
const onDrop = useCallback(acceptedFiles => {
const formData = new FormData()
formData.append('imgs', acceptedFiles)
try {
imgAjaxUploader.post('/store/admin/imgHandler.php', formData, {
headers: {
'Content-Type': 'mulipart/form-data'
}
}).then(data =>
console.log(data)
).catch(err => {
console.log(err)
return null
})
} catch (err) {
alert(err)
}
}, [])
const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop: onDrop, accept: 'image/jpeg, image/png' })
return (
<div {...getRootProps()} style={{ display: "inline-block" }}>
<input {...getInputProps()} />
{
isDragActive ?
<p>Drop the files here ...</p> :
<p>Drag 'n' drop some files here, or click to select files</p>
}
</div>
)
}
I found the solution. Multiple files need to be appended to the same name with a trailing [], in order to be compatible with PHP:
acceptedFiles.forEach(file => {
formData.append('imgs[]', file)
})
resource example 3

Ionic 3 Uncaught (in promise): [object Object]

I am new to Ionic 3 and mobile development. I am trying to connect a MySQL DB to my Ionic app and a PHP Restful API. I tested the API with Postman and it is working just fine, in order to implement it in Ionic I did the following,
I first made a provider named Authservice:
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import 'rxjs/add/operator/map';
let apiUrl = "http://localhost/api/"
/*
Generated class for the AuthServiceProvider provider.
See https://angular.io/guide/dependency-injection for more info on
and Angular DI.
*/
#Injectable()
export class AuthServiceProvider {
constructor(public http: HttpClient) {
console.log('Hello AuthServiceProvider Provider');
}
postData(credentials, type) {
return new Promise((resolve, reject) => {
let headers = new HttpHeaders();
this.http.post(apiUrl + type, JSON.stringify(credentials), { headers: headers })
.subscribe(res => {
resolve(res.json());
}, (err) => {
reject(err);
});
});
}
}
And a Signup page:
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { AuthServiceProvider } from '../../providers/auth-service/auth- service';
/**
* Generated class for the SignupPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
#IonicPage()
#Component({
selector: 'page-signup',
templateUrl: 'signup.html',
})
export class SignupPage {
responseData: any;
userData = {"username": "","password": "", "name": "","email": ""};
constructor(public navCtrl: NavController, public authServiceProvider: AuthServiceProvider) {
}
signUp() {
this.authServiceProvider.postData(this.userData, "signup").then((result) =>{
this.responseData = result;
console.log(this.responseData);
localStorage.setItem('userData', JSON.stringify(this.responseData));
});
}
goToLogin() {
this.navCtrl.pop();
}
}
When running this I am getting an Uncaught (in promise): [object Object] error as can be seen here.
UPDATE
I am now getting the following error:
Object { headers: {…}, status: 404, statusText: "Not Found", url: "http://localhost/PHP-SLIM-RESTFUL/API/signup", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://localhost/PHP-SLIM-RESTFUL/API/signup: 404 Not Found", error: "<html><head><title>404 Page Not Found</title><style>body{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;}h1{margin:0;font-size:48px;font-weight:normal;line-height:48px;}strong{display:inline-block;width:65px;}</style></head><body><h1>404 Page Not Found</h1><p>The page you are looking for could not be found. Check the address bar to ensure your URL is spelled correctly. If all else fails, you can visit our home page at the link below.</p>Visit the Home Page</body></html>" } signup.ts:36:6
postData(credentials, type) {
let headers = new HttpHeaders();
return this.http.post(apiUrl + type, JSON.stringify(credentials), { headers: headers });
}
this will return observable on the signup page, just subscribe it.
You can make use of Typescript's async methods to make your life easier
Your postData method in async
AuthServiceProvider:
public async postData(credentials, type): Promise<any> {
let headers = new HttpHeaders();
await this.http.post(apiUrl + type, JSON.stringify(credentials), { headers: headers }).toPromise();
}
Signup page:
public async signUp(): void {
try {
// request successful
this.responseData = await this.authServiceProvider.postData(this.userData, "signup");
console.log(this.responseData);
localStorage.setItem('userData', JSON.stringify(this.responseData));
}
catch(e) {
// some error occured, handle it here..
console.log(e);
}
}
Don't forget to import toPromise operator in AuthServiceProvider
import 'rxjs/add/operator/toPromise';
Try importing HttpModule in app.module.ts;
{import HttpModule } from '#angular/http'
Then add HttpModule to the imports;
imports :
[BrowserModule,
HttpModule,
IonicModule.forRoot(MyApp)
]

Cant show data on Ionic *ngfor

Hello i have a problem returning data on html file using an Ionic app. I use an auth-service.ts provider to connect to database and the results are returning fine on console-> network-> XHR (friendsNewsFeed)
On ionic serve i am getting error
trying to diff [object Object] only arrays and iterables are allowed
https://forum.ionicframework.com/t/problem-with-ngfor/121590
home.ts
import { Component, ViewChild } from "#angular/core";
import { NavController, App, AlertController } from "ionic-angular";
import { AuthService } from "../../providers/auth-service";
import { Common } from "../../providers/common";
import { Camera, CameraOptions } from "#ionic-native/camera";
#Component({ selector: "page-home", templateUrl: "home.html" })
export class HomePage {
public photos: any;
public base64Image: string;
public fileImage: string;
public userDetails: any;
public resposeData: any;
public dataSet: any;
public noRecords: boolean;
userPostData = {
uid: "",
token: "",
created: "",
message: ""
};
constructor(
public authService: AuthService
) {
const data = JSON.parse(localStorage.getItem("userData"));
this.userDetails = data.userData;
this.userPostData.uid = this.userDetails.uid;
this.userPostData.token = this.userDetails.token;
this.userPostData.created = "";
this.noRecords = false
this.getFeed();
}
ngOnInit() {
this.dataSet = [];
}
getFeed() {
this.common.presentLoading();
this.authService.postData(this.userPostData, "userNewsFeed").then(
result => {
this.resposeData = result;
if (this.resposeData) {
this.common.closeLoading();
this.dataSet = this.resposeData;
console.log(this.dataSet);
} else {
console.log("No access");
}
},
err => {
//Connection failed message
}
);
}
home.html
<ion-card *ngFor="let item of dataSet; let msgIndex = index">
<ion-item>
<ion-card-content>
<p [innerHTML]="item.message | linky"></p>
</ion-card-content>
</ion-item>
</ion-card>
auth-service.ts
import { Injectable } from '#angular/core';
import { Http, Headers } from '#angular/http';
import 'rxjs/add/operator/map';
let apiUrl = "http://localhost/PHP-Slim-Restful1/api/";
//let apiUrl = 'https://api.thewallscript.com/restful/';
/*
Generated class for the AuthService provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
#Injectable()
export class AuthService {
constructor(public http: Http) {
console.log('Hello AuthService Provider');
}
postData(credentials, type){
return new Promise((resolve, reject) =>{
let headers = new Headers();
this.http.post(apiUrl+type, JSON.stringify(credentials), {headers: headers}).
subscribe(res =>{
resolve(res.json());
}, (err) =>{
reject(err);
});
});
}
}
any hint?

Angular - how to get variable from local PHP file

I want to get variable from my getData.php file that is in src/assets folder of angular project.
<?php
...
echo json_encode('test');
?>
get-data.service :
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
#Injectable()
export class GetDataService {
constructor(private http: Http) {}
getTest(): Observable<any> {
return this.http.get('assets/getData.php')
.map(response => response.json());
}
}
app.component :
import { Component } from '#angular/core';
import { GetDataService } from './services/get-data.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private getDataService: GetDataService) { }
title = 'Run Chart Generator';
data;
getTestTwo() {
this.getDataService.getTest()
.subscribe(data => {
this.data = data;
console.log(this.data)
});
}
}
When I call function getTestTwo I've got:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
When I change php from echo json_encode('test') to echo 'test' and service from .map(response => response.json()) to .map(response => response) then I've got in console:
Object { _body: "<?php include('simple_html_dom.ph…", status: 200, ok: true, statusText: "OK", headers: Object, type: 2, url: "http://localhost:4200/assets/getDat…" }
How can I retrieve a variable from my php file?
#angular/cli: 1.4.1
#angular/core: 4.3.6
Your PHP file won't work under a NodeJS project.
You need to separate your Angular App from your server logic. Use Nginx or Apache to serve your PHP file, then you will be able to call it in your getTest() function.

Unable to post data from form to mysql in Angular 2

I am able to fetch the value I add in my textbox in a variable in my addoperation.ts file, but I am unable to send it to my database.
Here is my addoperation.ts code:
import { Component, OnInit } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { Headers, Http, HttpModule ,Response } from '#angular/http';
import 'rxjs/add/operator/map';
#Component({
selector: 'app-operationadd',
templateUrl: './operationadd.component.html',
styleUrls: ['./operationadd.component.css']
})
export class OperationaddComponent implements OnInit {
name="abc";
constructor(private http: Http) { }
ngOnInit() {
}
submitdata(){
console.log("Data Submitted");
console.log(this.name);
this.http.post('http://example.com/adv8/prod-api/crudtable-add.php', {name: this.name})
.map((res:Response) => res.json())
.subscribe(result =>{ });
}
}
and this is my addoperation.html
<form>
<div class="form-group">
<label for="name">First Name:</label>
<input type="text" class="form-control" #fname [(ngModel)]="name" name="firstname">
</div>
<button type="submit" class="btn btn-default" (click)="submitdata()">Submit</button>
</form>
My API is working fine, I have tested it on Chrome Postman. I pass a variable name: jess in the body and I get a SUCCESS message, but I am unable to save it from Angular.
After a lot of search i am able to post the data in my db, below I am pasting code , should be useful to someone in future.
Note: adding headers is important.
import { Component, OnInit } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { Headers, Http, HttpModule ,Response } from '#angular/http';
import 'rxjs/add/operator/map';
#Component({
selector: 'app-operationadd',
templateUrl: './operationadd.component.html',
styleUrls: ['./operationadd.component.css']
})
export class OperationaddComponent implements OnInit {
name="abc";
constructor(private http: Http) { }
ngOnInit() {
}
submitdata(){
console.log("Data Submitted");
console.log(this.name);
var body = "name=" + this.name;
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
this.http.post('http://example.com/adv8/prod-api/crudtable-add.php', body, {
headers: headers
})
.map(res => res.json())
.subscribe(
// data => this.saveJwt(data.id_token),
// err => this.logError(err),
() => console.log('Authentication Complete')
);
}
}

Categories