用formdata将数据发送到mysql

5vf7fwbs  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(505)

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

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;

问题是我无法在api中接收“nom”值,并且它不会显示任何错误。有人能帮我吗?

vm0i2vca

vm0i2vca1#

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);

}

希望上面的代码能起作用

相关问题