我只是想用我的更新配置文件api上传一个配置文件图片。我可以使用json(post(方法简单地通过body raw发送数据,但对于上传文件,我使用的是formdata,因为我不能发送任何数据。我得到的回复是,请提供输入详细信息。
这是我的api控制器代码
public function update_profile()
{
$this->default_file();
$responseData = array();
if(!empty($_POST['u_id']))
{
$id = $_POST['u_id'];
$userData['u_id'] = $id;
$userData['username'] = $_POST['username'];
$userData['usermob'] = $_POST['usermob'];
$userData['userlocation'] = $_POST['userlocation'];
$update_profile = $this->apm->update_profile($userData);
if(!empty($update_profile))
{
$id = $_POST['u_id'];
$userDetails = array();
$userDetails['id'] = $id;
$getUserDetails = $this->apm->getUserDetails($userDetails);
$responseData['u_id'] = $getUserDetails['result']['u_id'];
$responseData['username'] = $getUserDetails['result']['username'];
$responseData['useremail'] = $getUserDetails['result']['useremail'];
$responseData['usermob'] = $getUserDetails['result']['usermob'];
$responseData['userlocation'] = $getUserDetails['result']['userlocation'];
$responseArray = array(
'apiName' => 'update profile',
'version' => '1.0.0',
'responseCode' => 200,
'responseMessage' => "Your profile updated successfully",
'responseData' => $responseData
);
}
else
{
$responseArray = array(
'apiName' => 'update profile',
'version' => '1.0.0',
'responseCode' => 204,
'responseMessage' => "error in updating profile",
'responseData' => null//$responseData
);
}
}
else
{
$responseArray = array(
'apiName' => 'update profile',
'version' => '1.0.0',
'responseCode' => 204,
'responseMessage' => "Sorry, please provide your input details.",
'responseData' => null//$responseData
);
}
echo json_encode($responseArray);
die();
}
我提交的代码没有添加图像部分代码,以使用formdata检查简单的提交数据。
这是我的api模式代码
public function update_profile($userData)
{
return $this->db->update('users', $userData, array('u_id' => $userData['u_id']));
}
public function getUserDetails($userDetails = array())
{
$arrData = array();
if($userDetails['id'])
{
$where = "u_id='". $userDetails['id']."'";
$this->db->select('*');
$this->db->from('users');
$this->db->where($where);
$result = $this->db->get()->result_array();
if(!empty($result))
{
$arrData['result'] = $result[0];
}
else
{
$arrData['result'] = '';
}
}
return $arrData;
}
这是默认的文件代码
function default_file(){
header("Access-Control-Allow-Origin: * ");
header("Access-Control-Allow-Headers: Origin,Content-Type ");
header("Content-Type:application/json ");
$rest_json = file_get_contents("php://input");
$_POST = json_decode($rest_json,true);
}
请帮助我使用formdata运行代码,以便我可以通过该api上传图像。
FormData对象不编码为JSON(这是合理的,因为JSON不支持File数据类型,FormData的最大好处是它支持(。
FormData对象将被编码为multipart/form-data
,它将被PHP自动解析并用于填充$_POST
和$_FILES
。
不幸的是,您的代码($_POST = json_decode($rest_json,true);
(用试图解析为JSON的结果覆盖了您想要的数据,而不是JSON。
注意:使用FormData时,请确保不会覆盖请求中的Content-Type
标头。