使用 angular 从 ionic 上传图片到 php 文件
Uploading a picture from ionic with angular to a php file
问题:是我无法在客户端获取文件输入的数据,而是得到一个空数组。请看下面的结果。该文件的字段名称是 imageUrl
Ionic Angular代码:
addPlace(
title: string,
description: string,
imageUrl: string | File,
price: number,
dateFrom: Date,
dateTo: Date,
location: PlaceLocation
) {
let generatedId: string;
const newPlace = new Place(
Math.random().toString(),
title,
description,
imageUrl,
price,
dateFrom,
dateTo,
this.authService.userId,
location
);
return this.http
.post<{ id: string }>(environment.websiteApiPath + 'places/create.php', { ...newPlace })
.pipe(
switchMap(resData => {
generatedId = resData.id;
return this.places;
}),
take(1),
tap(places => {
newPlace.id = generatedId;
this.inPlaces.next(places.concat(newPlace));
})
);
}
PHP代码(create.php):
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
header('Content-Type: application/json; charset=utf-8');
$data = json_decode(file_get_contents('php://input'), true);
结果:它returns使用var_dump但imageUrl为空后的数组列表
<pre>array (
'id' => '0.2705669762462872',
'title' => '1',
'description' => '2',
'imageUrl' =>
array (
),
'price' => 3,
'availableFrom' => '2019-10-13T12:28:38.242Z',
'availableTo' => '2019-10-13T12:28:38.243Z',
'userId' => 'abc',
'location' =>
array (
'lat' => 14.5718818,
'lng' => 121.05366169999998,
'address' => '128 Pioneer St, Mandaluyong, Metro Manila, Philippines',
'staticMapImageUrl' => 'https://maps.googleapis.com/maps/api/staticmap?center=14.5718818,121.05366169999998&zoom=8&size=500x300&maptype=roadmap
&markers=color:red%7Clabel:Place%7C14.5718818,121.05366169999998
&key=AIzaSyBdYunI5O8tvnzEgwTsXFKQFjy6qa6Oyso',
),
)</pre>
客户端数据:我console.log()
发送http请求前的数据,下面是结果。
{title: "1", description: "2", price: 3, dateFrom: "2019-10-13T20:28:38.242+08:00", dateTo: "2019-10-13T20:28:38.243+08:00", …}
dateFrom: "2019-10-13T20:28:38.242+08:00"
dateTo: "2019-10-13T20:28:38.243+08:00"
description: "2"
image: File {name: "check-up-the-sound-insulation-in-Germany.jpg", lastModified: 1569910148000, lastModifiedDate: Tue Oct 01 2019 14:09:08 GMT+0800 (China Standard Time), webkitRelativePath: "", size: 6931, …}
location: {lat: 14.5718818, lng: 121.05366169999998, address: "128 Pioneer St, Mandaluyong, Metro Manila, Philippines", staticMapImageUrl: "https://maps.googleapis.com/maps/api/staticmap?cen…↵ &key=AIzaSyBdYunI5O8tvnzEgwTsXFKQFjy6qa6Oyso"}
price: 3
title: "1"
__proto__: Object
我 post 的问题已经解决。
我没有将用于请求 HTTP 请求的数据传递给 PHP 服务器,而是将 JSON 更改为 formData。
Ionic Angular代码:
addPlace(
title: string,
description: string,
imageUrl: string | File,
price: number,
dateFrom: Date,
dateTo: Date,
location: PlaceLocation
) {
let generatedId: number;
let generatedImage: string;
let fetchedUserId: number;
let newPlace: Place;
return this.authService.userId.pipe(
take(1),
switchMap(userId => {
fetchedUserId = userId;
return this.authService.token;
}),
take(1),
switchMap(token => {
if (!fetchedUserId) {
throw new Error('No user id found!');
}
newPlace = new Place(
null,
title,
description,
null,
price,
dateFrom,
dateTo,
fetchedUserId,
location
);
const uploadData = new FormData();
uploadData.append('title', title);
uploadData.append('description', description);
uploadData.append('image', imageUrl);
uploadData.append('price', price.toString());
uploadData.append('title', title);
uploadData.append('date_from', this.dateConvert(dateFrom));
uploadData.append('date_to', this.dateConvert(dateTo));
uploadData.append('user_id', fetchedUserId.toString());
uploadData.append('address', location.address );
uploadData.append('lat', location.lat.toString());
uploadData.append('lng', location.lng.toString());
uploadData.append('staticMapImageUrl', location.staticMapImageUrl );
return this.http
.post<{ id: number, image: string }>(`${environment.websiteApiPath}places/create.php?auth=${token}`, uploadData );
}),
switchMap(resData => {
generatedId = resData.id;
generatedImage = resData.image;
return this.places;
}),
take(1),
tap(places => {
newPlace.id = generatedId;
newPlace.imageUrl = generatedImage;
this.inPlaces.next(places.concat(newPlace));
})
);
}
我为 PHP 文件删除了以下代码:
$data = json_decode(file_get_contents('php://input'), true);
相反,我使用了 $_POST
和 $_FILES
问题:是我无法在客户端获取文件输入的数据,而是得到一个空数组。请看下面的结果。该文件的字段名称是 imageUrl
Ionic Angular代码:
addPlace(
title: string,
description: string,
imageUrl: string | File,
price: number,
dateFrom: Date,
dateTo: Date,
location: PlaceLocation
) {
let generatedId: string;
const newPlace = new Place(
Math.random().toString(),
title,
description,
imageUrl,
price,
dateFrom,
dateTo,
this.authService.userId,
location
);
return this.http
.post<{ id: string }>(environment.websiteApiPath + 'places/create.php', { ...newPlace })
.pipe(
switchMap(resData => {
generatedId = resData.id;
return this.places;
}),
take(1),
tap(places => {
newPlace.id = generatedId;
this.inPlaces.next(places.concat(newPlace));
})
);
}
PHP代码(create.php):
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
header('Content-Type: application/json; charset=utf-8');
$data = json_decode(file_get_contents('php://input'), true);
结果:它returns使用var_dump但imageUrl为空后的数组列表
<pre>array (
'id' => '0.2705669762462872',
'title' => '1',
'description' => '2',
'imageUrl' =>
array (
),
'price' => 3,
'availableFrom' => '2019-10-13T12:28:38.242Z',
'availableTo' => '2019-10-13T12:28:38.243Z',
'userId' => 'abc',
'location' =>
array (
'lat' => 14.5718818,
'lng' => 121.05366169999998,
'address' => '128 Pioneer St, Mandaluyong, Metro Manila, Philippines',
'staticMapImageUrl' => 'https://maps.googleapis.com/maps/api/staticmap?center=14.5718818,121.05366169999998&zoom=8&size=500x300&maptype=roadmap
&markers=color:red%7Clabel:Place%7C14.5718818,121.05366169999998
&key=AIzaSyBdYunI5O8tvnzEgwTsXFKQFjy6qa6Oyso',
),
)</pre>
客户端数据:我console.log()
发送http请求前的数据,下面是结果。
{title: "1", description: "2", price: 3, dateFrom: "2019-10-13T20:28:38.242+08:00", dateTo: "2019-10-13T20:28:38.243+08:00", …}
dateFrom: "2019-10-13T20:28:38.242+08:00"
dateTo: "2019-10-13T20:28:38.243+08:00"
description: "2"
image: File {name: "check-up-the-sound-insulation-in-Germany.jpg", lastModified: 1569910148000, lastModifiedDate: Tue Oct 01 2019 14:09:08 GMT+0800 (China Standard Time), webkitRelativePath: "", size: 6931, …}
location: {lat: 14.5718818, lng: 121.05366169999998, address: "128 Pioneer St, Mandaluyong, Metro Manila, Philippines", staticMapImageUrl: "https://maps.googleapis.com/maps/api/staticmap?cen…↵ &key=AIzaSyBdYunI5O8tvnzEgwTsXFKQFjy6qa6Oyso"}
price: 3
title: "1"
__proto__: Object
我 post 的问题已经解决。
我没有将用于请求 HTTP 请求的数据传递给 PHP 服务器,而是将 JSON 更改为 formData。
Ionic Angular代码:
addPlace(
title: string,
description: string,
imageUrl: string | File,
price: number,
dateFrom: Date,
dateTo: Date,
location: PlaceLocation
) {
let generatedId: number;
let generatedImage: string;
let fetchedUserId: number;
let newPlace: Place;
return this.authService.userId.pipe(
take(1),
switchMap(userId => {
fetchedUserId = userId;
return this.authService.token;
}),
take(1),
switchMap(token => {
if (!fetchedUserId) {
throw new Error('No user id found!');
}
newPlace = new Place(
null,
title,
description,
null,
price,
dateFrom,
dateTo,
fetchedUserId,
location
);
const uploadData = new FormData();
uploadData.append('title', title);
uploadData.append('description', description);
uploadData.append('image', imageUrl);
uploadData.append('price', price.toString());
uploadData.append('title', title);
uploadData.append('date_from', this.dateConvert(dateFrom));
uploadData.append('date_to', this.dateConvert(dateTo));
uploadData.append('user_id', fetchedUserId.toString());
uploadData.append('address', location.address );
uploadData.append('lat', location.lat.toString());
uploadData.append('lng', location.lng.toString());
uploadData.append('staticMapImageUrl', location.staticMapImageUrl );
return this.http
.post<{ id: number, image: string }>(`${environment.websiteApiPath}places/create.php?auth=${token}`, uploadData );
}),
switchMap(resData => {
generatedId = resData.id;
generatedImage = resData.image;
return this.places;
}),
take(1),
tap(places => {
newPlace.id = generatedId;
newPlace.imageUrl = generatedImage;
this.inPlaces.next(places.concat(newPlace));
})
);
}
我为 PHP 文件删除了以下代码:
$data = json_decode(file_get_contents('php://input'), true);
相反,我使用了 $_POST
和 $_FILES