1

Here is a bunch of my backend code that I have used to upload a file.

$app->post('/upload/{studentid}', function(Request $request, Response $response, $args) {

    $uploadedFiles = $request->getUploadedFiles();

    // handle single input with single file upload
    $uploadedFile = $uploadedFiles['filename'];
    if ($uploadedFile->getError() === UPLOAD_ERR_OK) {

        $extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);

        // ubah nama file dengan id buku
        $filename = sprintf('%s.%0.8s', $args["studentid"], $extension);

        $directory = $this->get('settings')['upload_directory'];
        $uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $filename);

        // simpan nama file ke database
        $sql = "UPDATE feepaid SET filename=:filename WHERE studentid=:studentid";
        $stmt = $this->db->prepare($sql);
        $params = [
            ":studentid" => $args["studentid"],
            ":filename" => $filename
        ];

        if($stmt->execute($params)){
            // ambil base url dan gabungkan dengan file name untuk membentuk URL file
            $url = $request->getUri()->getBaseUrl()."/Upload/".$filename;
            return $response->withJson(["status" => "success", "data" => $url], 200);
        } else {
            return $response->withJson(["status" => "failed", "data" => "0"], 200);
        } 
    }
});

When i tested using postman its working but im quite new to Angular. When i implement the api in my Angular apps its not working

enter image description here

And this is my code that i use to upload the file from angular application

  fileChange(event) {
    const fileList: FileList = event.target.files;
    if (fileList.length > 0) {
      const file: File = fileList[0];
      const formData: FormData = new FormData();
      formData.append('uploadFile', file, file.name);
      const headers = new Headers();
      /** In Angular 5, including the header Content-Type can invalidate your request */
      // headers.append('Content-Type', 'multipart/form-data');
      // headers.append('Accept', 'application/json');
      const id = sessionStorage.getItem('userId');
      // const options = new RequestOptions({ headers: headers });
      this.http.post('http://localhost:8080' + '/upload/' + id , formData)
        .subscribe(
          data => console.log('success'),
          error => console.log(error)
        );
    }

  }

And this is my example of testing using Postman

enter image description here

Why is it i have error? It seems like my file is not send to the backend and its return null value. Anyone can help me? Thank you

8
  • Is that API is working from PostMan or fiddler? Commented Apr 10, 2019 at 14:40
  • Its working on PostMan. I didnt test it on fiddler Commented Apr 10, 2019 at 14:43
  • Can you show us how you are sending data on the postman(Screen shot)? Commented Apr 10, 2019 at 14:46
  • I have already edited my question Commented Apr 10, 2019 at 14:51
  • Try: formData.append('filename', file); Commented Apr 10, 2019 at 14:52

1 Answer 1

1

You need to send the exact key-value pair for Form Data as you retrieve the key as filename so try changing:

formData.append('filename', file, file.name);
Sign up to request clarification or add additional context in comments.

7 Comments

Yeah already done that but it did not insert the file name to database. Any idea why?
If that is working from postman then the problem is in angular code itself
i tried console.log(data) but it returns null and yeah must be the angular code. Thank you anyway :)
Can you change the code from subscribe to Promise?
I have worked with FormData but My Backend was Web.API
|

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.