angularTS向PHP文件上传“文件为空”

时间:2018-08-20 22:12:12

标签: php angular file input angular6

我遇到了麻烦-无法将前端输入中的上传文件(文件似乎为空)发送到我的php后端,并且无法访问“文件”中的内容。

我的任务:当用户可以选择* .csv文件,在服务器上发送该文件,在SQL Table中解析并保存来自* .csv的数据并将其保存在其他内容中时,创建某种形式...

dataload.component.html:

<div>   <input type="file" (change)="doUpload($event)"/> </div>

dataload.component.ts:

import { Component } from '@angular/core';
import { HttpService } from '../http.service';

@Component({
  selector: 'app-dataload',
  templateUrl: './dataload.component.html',
  styleUrls: ['./dataload.component.css'],
  providers: [HttpService]
})
export class DataloadComponent {
  files: any;

  constructor(private http: HttpService) { }

  doUpload(event){
    let target = event.target || event.srcElement;
    this.files = target.files;

    console.log ('Files: ',this.files);

    const apiURL = 'There is my https://testAPI.php';

    this.http.post(apiURL, {'action': 'action','data': this.files})
      .subscribe(
        data => {
          console.log("Done. Response JSON: ",data);
        },
        error => {
          console.log('Error: ', error);
        }
      );
  }

}

testAPI.php

<?php
header ('Content-Type: text/html');
header ('Access-Control-Allow-Origin: *');
header ('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');

require_once("includes/connection.php");

$datafile = file_get_contents('php://input');
$obj = json_decode($datafile);

$action = $obj->{'action'};
$data = file_get_contents($obj->{'data'});


      $retArr = array(
                      'text' => "Action = ".$action,
                      'mess' => 'Data = '.$data
                    );

echo json_encode(array_values($retArr));
?>

结果:

当我在控制台中选择文件(* .csv)时,我看到: console.log screenshot

我尝试使用papaparse和ngx-papaparse,但是我在安装时遇到了问题,我尝试在前端解析以转换为JSON,但是我无法访问“ this.files”中的内容,因此尝试解析后端,但是在服务器端,同样的问题...

请帮助我,我很困惑:(

0 个答案:

没有答案