无法使用Angular和PHP上传图像

时间:2019-01-29 19:19:00

标签: php angular

我无法使用此代码在使用angular和php时上传图像。 请协助.. 我从php第2行收到错误未定义索引错误 角边

const formData = new FormData();
formData.append('date', this.uploadRequest.date.toString());
formData.append('description', this.uploadRequest.description);
formData.append('title', this.uploadRequest.title);

this.imageDetails.forEach((image, i) => {
  formData.append('images[' + i + ']', image.file);
});

const params = new HttpParams();

const options = {
  params: params,
  reportProgress: true,
};

const req = new HttpRequest('POST', '/api/upload', formData, options);
return this.http.request(req).subscribe();

php端

$target_file = "images/" . basename($_FILES["image"]["name"]);
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

$check = getimagesize($_FILES["image"]["tmp_name"]);
if (!empty($_FILES['image'])) {
if ($_FILES["image"]["size"] < 10485760 && $check !== false) {
    $uploadOk = 1;
    $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
    $image = time() . '.' . $ext;
    move_uploaded_file($_FILES["image"]["tmp_name"], 'images/' . 
$image);
    echo "Image uploaded successfully as " . $image;
} else {
    echo "Image Is too Large";
}
 } else {
echo "Image Is Empty";
}

1 个答案:

答案 0 :(得分:0)

您需要将代码放入if语句中。您正在尝试在if语句运行之前执行代码,而该代码对于if语句正确运行至关重要。

if (!empty($_FILES['image'])) {
$target_file = "images/" . basename($_FILES["image"]["name"]);
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
$check = getimagesize($_FILES["image"]["tmp_name"]);
if ($_FILES["image"]["size"] < 10485760 && $check !== false) {
    $uploadOk = 1;
    $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
    $image = time() . '.' . $ext;
    move_uploaded_file($_FILES["image"]["tmp_name"], 'images/' . 
$image);
    echo "Image uploaded successfully as " . $image;
} else {
    echo "Image Is too Large";
}
 } else {
echo "Image Is Empty";
}