Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 http.post FormData() to PHP to upload a file

I have a project using A2 CLI, and I'm trying to upload a file using an input tag with type="file". I have things functioning as far as the overall workflow goes, but I am having trouble getting the file data from client to server.

I have the following code in TypeScript:

myFnc(event){
    let fileList: FileList = event.target.files;
    if(fileList.length > 0) {
        let file: File = fileList[0];
        console.log(file);
        console.log(file.name);
        let formData:FormData = new FormData();
        formData.append('uploadFile', file, file.name);
        let headers = new Headers();
        /*
            this was the culprit:
            headers.append('Content-Type', 'multipart/form-data');
            worked for me by changing it to:
        */
            headers.append('enctype', 'multipart/form-data');
        headers.append('Accept', 'application/json');
        let options = new RequestOptions({ headers: headers });
        console.log(formData);
        console.log(options);
        this.http.post('./assets/data/upload-persona-document.service.php', formData, options)
            .map(res => res.json())
            .catch(error => Observable.throw(error))
            .subscribe(
                data =>{
                    console.log(data);
                },
                error =>{
                    console.log(error);
                }
            )
    }
}

I get no errors and get the results I'm inspecting in the console. (I understand that the console.log(formData) won't actually output formData's contents. I've tried .entries() but I've read that FormData methods are not well supported in TS.)

In upload-persona-document.service.php:

<?php
    $target_dir = "../docs/Personas/";
    $json = array();
    $postData = file_get_contents("php://input");
    $input = json_decode($postData);
    $json['input'] = $input;
    $json['post'] = ($_POST);
    $json['files'] = $_FILES;
    $target_file = $target_dir . basename($_FILES["uploadFile"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
    echo json_encode($json);
    // ...a bunch of code that will act on the data when I can finally get it correctly...

When I get the response back, I get:

[Log] {input: null, post: [], files: []} (main.bundle.js, line 1117)

I'm stumped at what I'm missing.

like image 254
Eric Avatar asked Jan 19 '26 09:01

Eric


1 Answers

So after a bit more digging and experimentation it turned out that I had to change Content-Type to enctype in the headers.append() line above (updated that bit.)

like image 114
Eric Avatar answered Jan 20 '26 22:01

Eric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!