简体   繁体   English

Angular 2 http.post FormData()向PHP上传文件

[英]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". 我有一个使用A2 CLI的项目,我正在尝试使用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: 我在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.) (我知道console.log(formData)实际上不会输出formData的内容。我已经尝试过.entries()但是我已经读过TS中没有很好地支持FormData方法。)

In upload-persona-document.service.php: 在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. 我对我所缺少的东西感到难过。

因此,经过一些挖掘和实验后,我发现我必须在上面的headers.append()行中将Content-Type更改为enctype(更新该位。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM