0

I've been struggling for hours now trying to upload an image to my server using PHP. I've only previoulsy worked in Angular 2 and now that I've changed to 8 I can't seem to get my old code to work and I suspect it is because the update of Http methods to HttpClient.

Here is the app.component.ts which calls the service with the input file:

let fileslen = $("#images")[0].files.length;
for(let i = 0; i < fileslen; i++){
  this.files.push($("#images")[0].files[i]);
  this.serviceImage.uploadImage(upload_url, this.files[i])
        .subscribe(
            response=> {
              this.imagesUrl.push(response["image"]);
            },
            error=>{
              alert('error:' + JSON.stringify(error));
            }
        );
}

This is my service function to upload the image:

uploadImage(url: string, file: File) {
        return Observable.create(observer => {
            let formData: FormData = new FormData();
            let xhr: XMLHttpRequest = new XMLHttpRequest();
            if (file != undefined) {
              formData.append("image", file, file.name);
              }
            xhr.onreadystatechange = () => {
              if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                  observer.next(JSON.parse(xhr.response));
                  observer.complete();
                } else {
                  observer.error(xhr.response);
                }
              }
            };
            xhr.open('POST', url, true);
            xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
            xhr.send(formData);
          });
      }

And finally this is the php file:

<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");

    $uploads_dir = 'uploads';
    $object = new stdClass();
    $errorMsg = "Error in image";
    $noFile = "No file";
    if(isset($_FILES['imagen'])){
        $tmp_name = $_FILES['image']['tmp_name'];
        $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
        $randNum = rand(0, 1000);
        $fileName = time() . sha1($_FILES['image']['name']. $randNum) . "." .$ext;
        if(move_uploaded_file($tmp_name, "$uploads_dir/$fileName")){
            $object->image = "$fileName";
            echo json_encode($object);
        }else{
            echo json_encode($errorMsg);
        }
    }else{
        echo json_encode($noFile);
    }
?>

The output of the console is: "Error in image"

The server error log shows this:

[Mon Sep 23 13:38:53.573923 2019] [proxy_fcgi:error] 
[pid 17680:tid 140606869325568] 
[client 213.127.0.0:37223] 
AH01071: Got error 'PHP message: PHP Warning:
move_uploaded_file(uploads/156923873339c6f3f02e62236530e6b49efbafabacd958828a.pdf): 
failed to open stream: 
No such file or directory in /var/www/clients/client490/web1568/web/app/php/upload_image.php 
on line 15\nPHP message: PHP Warning:  move_uploaded_file(): 
Unable to move '/var/www/clients/client490/web1568/tmp/phpIdHxdy' 
to 'uploads/156923873339c6f3f02e62236530e6b49efbafabacd958828a.pdf' 
in /var/www/clients/client490/web1568/web/app/php/upload_image.php 
on line 15\n', 
referer: {url}
Geneviv
  • 11
  • 1
  • 1
    Any console errors? What does the request response look like in the console? – Brett Gregson Sep 23 '19 at 11:19
  • If you have an issue, you need to properly explain it. "Not working" is a way too broad description. What happens? What debugging have you done? – M. Eriksson Sep 23 '19 at 11:20
  • Your JS are expecting the result to be JSON, but you're just outputting strings "as is" on error. Try returning the error messages as json as well. – M. Eriksson Sep 23 '19 at 11:25
  • I did it and the error that is returning is the "Error in img" – Geneviv Sep 23 '19 at 11:39
  • So it failed to move the file. Make sure you have the correct target folder and that the user the web server runs as can write to the folder. Have you checked the web servers error log to see if you get any error messages that might explain the issue? – M. Eriksson Sep 23 '19 at 11:46
  • Ive updated the question with the error log. – Geneviv Sep 23 '19 at 12:01
  • Try: `if(move_uploaded_file($tmp_name, getcwd() . "/$uploads_dir/$fileName")){` – Brett Gregson Sep 23 '19 at 14:45

0 Answers0