0

I am trying to upload images from my Angular 8+ frontend to my php backend and sending text data works without a problem, but wanting to send image files to a folder in my wamp directory, no cigar unfortunately...

It worked earlier, but this morning it decided it did not want to work anymore. I tried adding to the CORS headers, but nothing seems wrong there.

html:

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

component:

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();
  }

service:

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');
?>

imageUpload.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";
}

Expected result: Just do the upload

Actual result: 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.

and

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

1 Answer 1

2

try this

Add below Code in .htaccess file PHP(Server) side

<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>

Angular Code

page.html

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

npm install

"rxjs": "~6.5.1", //npm i [email protected] --save
"rxjs-compat": "^6.5.2" // npm i [email protected] --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);
    }) 
  }
Sign up to request clarification or add additional context in comments.

2 Comments

how did you get that concatMap() from rxJs going?
what angular version did you use?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.