用Ionic / angular将图像上传到php脚本不起作用

问题描述 投票:0回答:1

我正在尝试让我的Ionic应用程序上传用户选择的图像。我读了几本教程,但是我没有设法使它起作用。我希望该应用程序在浏览器中运行,因此我并没有实现仅在移动平台上运行的解决方案。

我的角度组件将发布请求发送到托管以下php-script的服务器,并根据指定创建“ uploads”文件夹。但是每次我要上传文件时,都会收到“上传文件时出错,请重试!”我的PHP脚本中指定的错误消息。

我认为我可能以错误的格式发送数据,但是可以弄清楚该怎么做。

任何想法,我的问题可能是什么?

<?php
header('Access-Control-Allow-Origin: *');
$target_path = "uploads/";

$target_path = $target_path . basename( $_FILES['file']['name']);


if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
    header('Content-type: application/json');
    $data = ['success' => true, 'message' => 'Upload and move success'];
    echo json_encode( $data );
} else{
    header('Content-type: application/json');
    $data = ['success' => false, 'message' => 'There was an error uploading the file, please try again!'];
    echo json_encode( $data );
}

?>

这是我在组件中的Typescript代码:


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


@Component({
  selector: 'app-erledigt-modal',
  templateUrl: './erledigt-modal.component.html',
  styleUrls: ['./erledigt-modal.component.scss'],
})
export class ErledigtModalComponent implements OnInit {

   constructor(private http: HttpClient) { }

  selectedFile = null;

  ngOnInit() {

  }

  onFileChanged(event) {
      this.selectedFile = <File>event.target.files[0]
  }

  onUpload() {

    const uploadData = new FormData();
    uploadData.append('image', this.selectedFile, this.selectedFile.name);
    this.http.post('https://...MyAPI.../upload.php', uploadData).subscribe(res => {
      console.log(res);
    });
  }


}

我还尝试了以下POST请求,但均未成功:

this.http.post('https://...MyAPI.../upload.php', this.selectedFile).subscribe(res => {
      console.log(res);
});
  } 

我的HTML看起来像这样:

<input type="file" (change)="onFileChanged($event)">
<button type="button" (click)="onUpload()">Upload</button>
php angular typescript ionic-framework image-uploading
1个回答
0
投票

我找到了解决方法。...

if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path))

uploadData.append('image', this.selectedFile, this.selectedFile.name);

不能一起使用,因为我在formdata中使用的名称是'image',而PHP脚本需要'file'..因此将'image'更改为'file'是解决方案...

© www.soinside.com 2019 - 2024. All rights reserved.