【问题标题】:CORS headers not working for File Upload from Angular to PHPCORS 标头不适用于从 Angular 到 PHP 的文件上传
【发布时间】:2019-10-02 05:22:37
【问题描述】:

我正在尝试将图像从我的 Angular 8+ 前端上传到我的 php 后端并发送文本数据没有问题,但是想将图像文件发送到我的 wamp 目录中的文件夹,不幸的是没有雪茄......

它早些时候工作,但今天早上它决定不再工作。我尝试添加到 CORS 标头,但那里似乎没有任何问题。

html:

<input type="button" value="Test" (click)='Advertise($event.target.files)'>

组件:

ToUpload()
  {
    let images = this.carImages.nativeElement;
    let j=10;
    for(let i of images.files)
    { 
      console.log(i);
      if(i.type=='image/jpeg')
      {
        let frmData = new FormData();
        frmData.append('file',i,(j+'.jpg').toString());
        this.uploadService.UploadImages(frmData).subscribe(val=>
        {
        })
      }
      if(i.type=='image/png')
      {
        let frmData = new FormData();
        frmData.append('file',i,(j+'.png').toString());
        this.uploadService.UploadImages(frmData).subscribe(val=>
        {
        })
      }
      j++;
    }

  }
  Advertise(files:FileList)
  {
    this.ToUpload();
  }

服务:

UploadImages(image:FormData):Observable<any>
  {
    return this.httpClient.post(this.apiURL+"/api/BLL/imageUpload.php?action=upload",image) as Observable<any>;
  }

CORS_Headers.php

<?php
// Default Header
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization,Content-Range, Content-Disposition, Content-Description');
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Credentials: true");
header("MIME-Version: 1.0");
header("Content-type:text/html;charset=UTF-8");
// Response type header
header('Content-Type: application/json');
?>

图片上传.php

<?php
require_once '../BLL/CORS_Headers.php';

//require '../DAL/DBHandler.php';

//use DAL\DBHandler;

$action=$_GET['action'];
if($action=='upload')
{
    $tempPath = $_FILES['file']['tmp_name'];

    // Get File Name
    $actualName = $_FILES['file']['name'];

    // New path
    $actualPath = '../Images/' . $actualName;
    //$tempPath = compressImage($tempPath,$actualPath,60);
    // Move File into new path
    move_uploaded_file($tempPath, $actualPath)
    // Get real path of moved file here
    $realPath = realpath(__DIR__ . '/' . $actualPath);
    // Delete the file
    echo "Uploaded";
}

预期结果:只需上传

实际结果:Access to XMLHttpRequest at 'http://localhost:3000/api/BLL/imageUpload.php?action=upload' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://localhost:3000/api/BLL/imageUpload.php?action=upload", ok: false, …}

【问题讨论】:

    标签: php angular typescript wamp wampserver


    【解决方案1】:

    试试这个

    在 .htaccess 文件 PHP(Server) 端添加以下代码

    <IfModule mod_headers.c>
        Header set Access-Control-Allow-Origin "*"
        Header always set Access-Control-Allow-Methods "POST, GET, PUT, DELETE, OPTIONS"
        Header always set Access-Control-Allow-Headers "X-Requested-With, content-type"
    </IfModule>
    

    角度代码

    page.html

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

    npm 安装

    "rxjs": "~6.5.1", //npm i rxjs@6.5.1 --save
    "rxjs-compat": "^6.5.2" // npm i rxjs-compat@6.5.2 --save
    

    page.ts

    import 'rxjs/add/observable/from';
    import 'rxjs/add/observable/of';
    import 'rxjs/add/operator/concatMap';
    
    fileUpload(event){
          let formData = new FormData();
              formData.append('file', event.target.files[0]);
    
          this.ImageUpload(formData).subscribe(val => {
            //enter custom code
          })
    }
    
    
    ImageUpload(formData):Observable<any>{
        var token = localStorage.getItem('keyToken');
        const myHeaders = new HttpHeaders({ 'Authorization': token });
        return this.http
        .post(URL, formData,{headers:myHeaders})
        .concatMap(data=>{
          return Observable.of(data);
        }) 
      }
    

    【讨论】:

    • 你是如何从 rxJs 获得 concatMap() 的?
    • 你用的是什么角度版本?
    猜你喜欢
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多