I'm having a problem uploading images. CKEditor keeps throwing an "Incorrect server response" error when using the drag and drop Upload Image addon.
I've added the following lines to my ckeditor config.js file:
config.extraPlugins = 'uploadimage';
config.imageUploadUrl = './scripts/ckImageUpload.php';
config.extraPlugins = 'image2';
And my ckImageUpload.php script is:
con = dbConnect();
$id = $_GET['edit'];
$time = new DateTime;
$fileName = $time->format(DateTime::ATOM).pathinfo($_FILES['upload']['name'], PATHINFO_EXTENSION);
$url = './images/uploaded/'.$fileName;
if(move_uploaded_file($_FILES['upload']['tmp_name'], $url)) {
$data = ['uploaded' => 1, 'fileName' => $filename, 'url' => $url];
$query = 'INSERT INTO postImages (
parentID,url
) VALUES (
"'.$id.'",
"'.$url.'"
)';
if(!mysqli_query($con, $query)){
$error = 'Insert query failed';
$data = array('uploaded' => 0, 'error' => array('message' => $error));
}
} else {
$error = 'There was an error uploading the file';
$data = array('uploaded' => 0, 'error' => array('message' => $error));
}
echo json_encode($data);
If I fake it and remove everything except the following lines, and place an image called image.jpg in the correct location the error goes away and the image appears within the editor as it should:
$data = ['uploaded' => 1, 'fileName' => 'image.jpg', 'url' => './images/uploaded/image.jpg'];
echo json_encode($data);
Instead of trusting the std. json_encode, sending an actual JSON response works.
Changing that simple
echo json_encode($data);
into:
return new Symfony\Component\HttpFoundation\JsonResponse($data);
will get this working.
Related
I am just trying to upload a profile picure with my update profile api. I can send data simply by body raw using json (post) method but for uploading file i am using formdata and in that i can't send any data. i get only response that please provide input details.
Here is my api controller code
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();
}
i am submitting the code without adding the image part code to check simple submit data using formdata.
Here is my api modal code
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;
}
This is default file code
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);
}
Please help me in running my code using formdata so that i can upload a image through that api.
FormData objects are not encoded as JSON (which is sensible since JSON doesn't support the File data type and the big benefit of FormData is that it does).
FormData objects will be encoded as multipart/form-data which will be automatically parsed by PHP and used to populate $_POST and $_FILES.
Unfortunately, your code ($_POST = json_decode($rest_json,true);) overwrites the data you want with the results to trying to parse, as JSON, something which isn't JSON.
NB: When using FormData, make sure you don't overwrite the Content-Type header on the request.
I am very new to PHP, I am using PHP Slim Framework. I have tried to research through Stack Overflow but didn't find an answer that answered my question.
I am trying add a car description on my school project, it captures all the fields well but the image is not being saved to the database and not being uploaded to the images folder, instead it saves the image in the database as a json as:
{
"car_images":
[
{
"file":"C:\\xampp\\tmp\\php8F2B.tmp"
}
]
}
instead of a91cffe8c9b5082f.jpg.
when I try to view the image in a browser on my localhost it goes to this path:
http://localhost/carbac/public/category_image/%7B%22car_images%22:[%7B%22file%22:%22C://xampp//tmp//php8F2B.tmp%22%7D]%7D
What could I be doing wrong?
Below is my function for capturing the details:
public function add(Request $request, Response $response, $args){
$car_category_id = $request->getParam('car_category_id');
$name = $request->getParam('name');
$description = $request->getParam('description');
$price = $request->getParam('price');
$mileage = $request->getParam('mileage');
$fuel_type = $request->getParam('fuel_type');
$transmission = $request->getParam('transmission');
$fuel_economy = $request->getParam('fuel_economy');
$air_condition = $request->getParam('air_condition');
$hourly_price = $request->getParam('hourly_price');
$daily_price = $request->getParam('daily_price');
$year = $request->getParam('year');
$directory = __DIR__ . '/../../../public/profile_image';
$uploadedFiles = $request->getUploadedFiles()['category_image'];
$avater = $request->getUploadedFiles();
foreach($uploadedFiles as $uploadedFile) {
if ($uploadedFile->getError() === UPLOAD_ERR_OK) {
$avater[] = \App\Helpers\FileUpload::moveUploadedFile($directory, $uploadedFile, ['png', 'jpeg', 'gif', 'jpg']);
} else {
$Flash = new Flash();
$Flash->addMessage('message', "Sorry, something went wrong from our end, please notify site owner");
$Flash->addMessage('status', "callout-danger");
return $response->withRedirect($this->router->pathFor('car_description'));
}
}
if( ! $avater ) {
$Flash = new Flash();
$Flash->addMessage('message', "Sorry, Please make image you are uploading is either a 'png', 'jpeg' or 'gif'");
$Flash->addMessage('status', "callout-danger");
return $response->withRedirect($this->router->pathFor('car_description'));
}
$car_description = CarDescription::create([
'car_category_id' => $car_category_id,
'name' => $name,
'description' => $description,
'year' => $year,
'mileage' => $mileage,
'price' => $price,
'fuel_type' => $fuel_type,
'transmission' => $transmission,
'fuel_economy' => $fuel_economy,
'air_condition' => $air_condition,
'hourly_price' => $hourly_price,
'daily_price' => $daily_price,
'images' => json_encode($avater)
]);
I have a form in which I am submitting email and a attachment in database. The form is submitting but I can not get the name of the file in database. How can I get the name of the file which I have uploaded.
here is my code
$ImageSavefolder = "dashboard/document/"; //folder name where image saves
$uploadfile = $ImageSavefolder . basename($_FILES['uploadDoc']['name']);
move_uploaded_file($_FILES["uploadDoc"]["tmp_name"] , $uploadfile);
$query1 = "INSERT into docs (docs_name, userid, appointmentid) VALUES('$uploadfile', '$userid', '$appointid')";
$inserted1 = mysqli_query($this -> connection, $query1);
if($inserted1 == 1 ){
$json = array(
"status" => '200',
"data" => array("success" => "Doc uploaded successfully.")
);
} else {
$json = array(
"status" => '400',
"data" => array("error" => "File too large. File must be less than 2MB.")
);
}
It's all here: http://php.net/manual/en/features.file-upload.post-method.php
Just read first entry ($_FILES['userfile']['name']).
We have API which receives images converted in base64 string. Our mobile application consumes too much RAM during the conversion process (to base64), now we need to upload image as multipart. I developed the mobile part but I'm stuck with the PHP API. We switched from volley to Retrofit because volley did not support multipart upload.
What do I need to change in the script that receives the multipart image upload?
<?php
//header('Content-Type : bitmap; charset=utf-8');
//header('Content-Type: application/json');
if (isset($_POST["encoded_string"])) {
//encoded_string -> base64 string sent from mobile phone
$encoded_string = $_POST["encoded_string"];
$image_name = $_POST["image_name"];
$decoded_string = base64_decode($encoded_string);
$path = 'images/' . $image_name;
if (!file_exists('images')) {
mkdir('images', 0777, true);
}
$file = fopen($path, 'wb');
$is_written = fwrite($file, $decoded_string);
fclose($file);
if ($is_written > 0) {
$connection = mysqli_connect('localhost', 'root', '', 'test');
if ($connection) {
$query = "INSERT INTO photos(name,path) values('$image_name','$path');";
$result = mysqli_query($connection, $query);
if ($result) {
echo json_encode(array(
"response" => "Success! Image is succefully uploaded!.",
"result" => "success"
));
} else {
echo json_encode(array(
"response" => "Error! Image is not uploaded.",
"result" => "error"
));
}
mysqli_close($connection);
} else {
echo json_encode(array(
"response" => "Error! No database connection!",
"result" => "error"
));
}
}
} else {
echo json_encode(array(
"response" => "Error! Please insert data!",
"result" => "error"
));
}
?>
Have a look at move_uploaded_file() function of php and the $_FILES array.
Example code plenty on this site.
If you want add multipart upload in backend you should make next changes:
<?php
//header('Content-Type : bitmap; charset=utf-8');
//header('Content-Type: application/json');
if (isset($_POST["encoded_string"])) {
//encoded_string -> base64 string sent from mobile phone
if (!file_exists('images')) {
mkdir('images', 0777, true);
}
$connection = mysqli_connect('localhost', 'root', '', 'test');
if (!$connection) {
echo json_encode(array(
"response" => "Error! No database connection!",
"result" => "error"
));
die;
}
$responses = array();
foreach ($_FILES["pictures"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$image_name = $_FILES["pictures"]["name"][$key];
$path = 'images/' . $image_name;
if (move_uploaded_file($tmp_name, path)) {
$query = "INSERT INTO photos(name,path) values('$image_name','$path');";
$result = mysqli_query($connection, $query);
if ($result) {
$responses[] = array(
"response" => "Success! Image is succefully uploaded!.",
"result" => "success"
);
} else {
$responses[] = array(
"response" => "Error! Image is not uploaded.",
"result" => "error"
);
}
}
} else {
$responses[] = array(
"response" => "Error! Please insert data!",
"result" => "error"
);
}
}
mysqli_close($connection);
echo json_encode(array(
'responses' => $responses
));
}
Also, make shore you use post request with multipart format (it should have header Content-Type: multipart/form-data and bi in right format - https://ru.wikipedia.org/wiki/Multipart/form-data). Hope it help you.
I have a Zend Form and offer the option to upload multiple files with the form. I use dropzone.js. When I upload a single file, everything works fine, I get the Post data and the file gets renamed and moved into the correct folder, but as soon I upload 2 files, I get an Error Message: Notice: Array to string conversion which points to $upload->addFilters('File\Rename'.....
What am I doing wrong here? I have everything in a foreach loop, should this not solve the issue? I can not find a solution for it. Anyone got a tip for me?
Here my Sourcecode so far:
$upload = new \Zend\File\Transfer\Adapter\Http();
// Limit the amount of files
$upload->addValidator('Count', false, 2);
// Limit the MIME type of all given files to gif and jpeg images
$upload->addValidator('MimeType', false, array('image/gif', 'image/jpeg',));
if (!$upload->isValid()) {
$data = new JsonModel(array(
'success' => "failed",
'message' => "validation failed",
));
return $data;
}else{
$files = $upload->getFileInfo();
$upload->setDestination('./public/uploads/tmp/');
// loop through the file array
foreach ($files as $file => $info) {
$file_ext = #strtolower(#strrchr($originalName,"."));
$file_ext = #substr($file_ext, 1); // remove dot
$newFilename = md5(uniqid(rand(), true)) .time(). '.' . $file_ext;
$upload->addFilter('File\Rename',
array('target' => $upload->getDestination() . DIRECTORY_SEPARATOR . $newFilename,
'overwrite' => true));
if (!$upload->receive()) {
$data = new JsonModel(array(
'success' => "upload failed",
));
}else{
$data = new JsonModel(array(
'success' => "upload ok",
));
}
return $data;
} // end foreach
}