使用formData将数据发送到mysql

时间:2018-04-19 13:10:11

标签: php mysql angular api httprequest

我在从服务接收数据时遇到问题。

insertService(nom: string, fileToUpload: File) {
    console.log(nom);
    const url = 'http://localhost/Admin/src/api/api.php?action=insertService&nom=' + nom ;
    const formData: FormData = new FormData();
    formData.append('nom', nom);
    formData.append('image', fileToUpload, fileToUpload.name);
    return this.http.post(url, formData);
}

这是API

$rest_json = file_get_contents("php://input");
$_POST = json_decode($rest_json, true);

$nom = $_POST['nom'];
$image = $_POST['image'];

$filetmp = $_FILES["image"]["tmp_name"];
$filename = $_FILES["image"]["name"];
$filepath = "../assets/img/" . $_FILES["image"]["name"];

move_uploaded_file($filetmp, $filepath);

$query = 'INSERT into etservice(nom_service,date_s,image_ser) values("' . $nom . '","' . Null . '","' . $filepath . '")';
$result = $db->query($query);
if ($result === TRUE) {
    $res = "Inserted'$nom '";
    echo json_encode($res);
} else {
    echo json_encode("Error" . $query . "<br>" . $db->error);
}
break;

问题是我无法收到&#34; nom&#34; API中的值,它不会向我显示任何错误。 任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

I think you are missing the headers part of the provided code:

    insertService(nom: string, fileToUpload: File) {
    console.log(nom);
    const url = 'http://localhost/Admin/src/api/api.php?action=insertService&nom=' + nom ;
    const formData: FormData = new FormData();
    formData.append('nom', nom);
    formData.append('image', fileToUpload, fileToUpload.name);

        let headers = new Headers();
        headers.append('enctype', 'multipart/form-data');
        headers.append('Accept', 'application/json');
       // headers.append('Authorization', 'Bearer ' + Authtoken); 
// uncomment if needed
        let options = new RequestOptions({headers: headers});

        return this.http.post(url, formData, , options);

}

希望上面的代码能够正常运行