[英]Can't post image from ionic to express server using php
我正在嘗試將圖片從離子應用程序上傳到快遞服務器。 當我使用郵遞員對其進行測試時,該服務器可以正常工作,但是從離子的角度來看,它不起作用(由於沒有Mac,因此無法在iPhone上進行測試)。
這是代碼:
import { ActionSheetController, ToastController, Platform, LoadingController, Loading } from 'ionic-angular';
import { Injectable } from '@angular/core';
import { ApiService } from '../services/api.service';
import { File } from '@ionic-native/file';
import { Transfer, TransferObject } from '@ionic-native/transfer';
import { FilePath } from '@ionic-native/file-path';
import { Camera } from '@ionic-native/camera';
import { Http, Headers } from '@angular/http';
declare var cordova: any;
@Injectable()
export class imageService {
loading: Loading;
image: string = null;
imageSelected: Boolean = false;
constructor(private http: Http, private camera: Camera, private transfer: Transfer, private file: File, private filePath: FilePath, public actionSheetCtrl: ActionSheetController, public toastCtrl: ToastController, public platform: Platform, public loadingCtrl: LoadingController) { }
takePicture(sourceType) {
// Create options for the Camera Dialog
var options = {
destinationType: this.camera.DestinationType.DATA_URL,
quality: 50,
sourceType: sourceType,
saveToPhotoAlbum: false,
correctOrientation: true
};
// Get the data of an image
this.camera.getPicture(options).then((imageData) => {
this.image = "data:image/jpeg;base64," + imageData;
this.presentToast('Selected Image');
alert("selected image");
this.imageSelected = true;
this.uploadImage();
}, (err) => {
this.presentToast('Error while selecting image.');
alert("error selecting");
});
}
private presentToast(text) {
let toast = this.toastCtrl.create({
message: text,
duration: 3000,
position: 'top'
});
toast.present();
}
uploadImage() {
if (this.imageSelected) {
this.presentToast("image is selected");
alert("image is selected");
this.http.post("http://appserver.com:8080/sql_api/profilePic", { image: this.image }, function(err, res){
if(err){
console.log("ERROR", err);
alert("Error with request");
}else{
console.log(res);
alert("success in callback");
this.presentToast('image posted successfully');
}
});
}
else {
this.presentToast('image not selected');
alert("image not selected");
}
}
}
使用它時,我沒有從服務器日志中收到任何發布請求。
這里沒有提供服務器代碼或郵遞員請求標頭信息,因此我假設您的服務器可以處理json請求。
您的代碼有什么問題
uploadImage() {
if (this.imageSelected) {
this.presentToast("image is selected");
alert("image is selected");
/* http method on angular is not a simple callback
its an observable and this request missing headers also
this request will not executed if you not calling subsribe on angular
http */
this.http.post("http://appserver.com:8080/sql_api/profilePic",{ image: this.image }, function(err, res){
if(err){
console.log("ERROR", err);
alert("Error with request");
}else{
console.log(res);
alert("success in callback");
this.presentToast('image posted successfully');
}
});
/* change your request like this and make sure your express server
can handle json request and parse the body
you can look at express body parser to handle another request */
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post("http://appserver.com:8080/sql_api/profilePic",
{ image: this.image },{headers:headers})
.subscribe((res)=>{
// request success here is your response
console.log(res);
alert("success in callback");
this.presentToast('image posted successfully');
},
err =>{
// handler error
console.log("ERROR", err);
alert("Error with request");
}
)
}
}
我建議您制作另一個組件或離子頁面,以將ui組件與imageService分開。 因為UI交互不應包含在角度服務中。
圖像service.ts
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
@Injectable()
export class ImageService {
constructor(private http: Http ) { }
uploadImage(image) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post("http://appserver.com:8080/sql_api/profilePic",{
image: image },{headers:headers});
}
}
ImagePage.ts
import { Component } from '@angular/core';
import { NavController, NavParams, AlertController, LoadingController, ActionSheetController, ToastController, Platform,Loading} from 'ionic-angular';
import { ImageService } from './image-service';
import { Camera } from '@ionic-native/camera';
/*
Generated class for the ImagePage.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
*/
@Component({
selector: 'app-image',
templateUrl: 'image.html',
providers: [ImageService]
})
export class ImagePage {
loading: Loading;
image: string = null;
imageSelected: Boolean = false;
constructor(private camera: Camera, public actionSheetCtrl:
ActionSheetController, public toastCtrl: ToastController,
public platform: Platform, public loadingCtrl: LoadingController,
private imageService:ImageService) {}
takePicture(sourceType) {
// Create options for the Camera Dialog
var options = {
destinationType: this.camera.DestinationType.DATA_URL,
quality: 50,
sourceType: sourceType,
saveToPhotoAlbum: false,
correctOrientation: true
};
// Get the data of an image
this.camera.getPicture(options).then((imageData) => {
this.image = "data:image/jpeg;base64," + imageData;
this.presentToast('Selected Image');
alert("selected image");
this.imageSelected = true;
this.imageService.uploadImage(this.image)
.subscribe((res)=>{
// request success here is your response
console.log(res);
alert("success in callback");
this.presentToast('image posted successfully');
},
err =>{
// handler error
console.log("ERROR", err);
alert("Error with request");
});
}, (err) => {
this.presentToast('Error while selecting image.');
alert("error selecting");
});
}
private presentToast(text) {
let toast = this.toastCtrl.create({
message: text,
duration: 3000,
position: 'top'
});
toast.present();
}
}
測試
如果您未在實際硬件上進行測試,請使用離子服務,請通過訪問該離子博客來處理cors問題,以處理Ionic中的CORS問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.