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.
Related
Im following some tutorial to upload file on server by php api. I need to send some data with file. Like with file i want to send a name. So it will generate folder by that name and save file in that folder.
home.ts
onFileSelect(event) {
if (event.target.files.length > 0) {
const file = event.target.files[0];
this.form.get('avatar').setValue(file);
}
}
onSubmit() {
console.log(this.backUrl);
name = this.backUrl;
console.log(name);
const formData = new FormData();
formData.append('avatar', this.form.get('avatar').value);
this.uploadService.uploadFile(formData).subscribe(
(res) => {
this.uploadResponse = res;
console.log(res);
},
(err) => {
console.log(err);
}
);
}
service.ts
public uploadFile(data,) {
let uploadURL = 'http://api.igiinsurance.com.pk:8888/file_upload/upload.php';
return this.httpClient.post<any>(uploadURL, data);
}
upload.php
<?php
header('Content-Type: application/json; charset=utf-8');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
$response = array();
$upload_dir = 'uploads';
$server_url = 'http://api.igiinsurance.com.pk:8888';
if($_FILES['avatar'])
{
$avatar_name = $_FILES["avatar"]["name"];
$avatar_tmp_name = $_FILES["avatar"]["tmp_name"];
$error = $_FILES["avatar"]["error"];
if($error > 0){
$response = array(
"status" => "error",
"error" => true,
"message" => "Error uploading the file!"
);
}else
{
$random_name = rand(1000,1000000)."-".$avatar_name;
$upload_name = $upload_dir.strtolower($random_name);
$upload_name = preg_replace('/\s+/', '-', $upload_name);
if(move_uploaded_file($avatar_tmp_name , $upload_name)) {
mkdir("upload/testing3");
$response = array(
"status" => "success",
"error" => false,
"message" => "File uploaded successfully",
"url" => $server_url."/".$upload_name
);
}else
{
$response = array(
"status" => "error",
"error" => true,
"message" => "Error uploading the file!"
);
}
}
}else{
$response = array(
"status" => "error",
"error" => true,
"message" => "No file was sent!"
);
}
echo json_encode($response);
?>
I want to send name with file. And in php that name will be the folder of that file. Example All files are now saving in ""uploads"" folder. I need file save in upload>name>file-here. Any one can help in code so please
handleInputChange(event: any) {
const image = event.target.files[0];
const reader = new FileReader();
if (!image.type.match(/image-*/)) {
this.Toastr.error('Image are not valid.', 'Failed!');
return;
} else {
this.photo = image;
reader.onload = (event1: ProgressEvent) => {
this.url = (<FileReader>event1.target).result;
};
reader.readAsDataURL(event.target.files[0]);
this.selectedFile = event.target.files[0];
this.validateImage = false;
}
}
this.ServiceName.saveNewsData("api_url", this.selectedFile).subscribe((response: any) => {
if (response.status == true) {}})
saveNewsData(url, photo) {
const data = new FormData();
data.append('featuredImage', photo);
return this.http.post(url, data,{ headers: header })
.map(response => response)
.catch(this.handleError);
}
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.
I'm trying to update the content of the file. Use the PHP function:
function updateFile($service, $fileId, $newTitle, $newDescription, $newMimeType, $newFileName, $newRevision) {
try {
// First retrieve the file from the API.
$file = $service->files->get($fileId);
// File's new metadata.
$file->setTitle($newTitle);
$file->setDescription($newDescription);
$file->setMimeType($newMimeType);
// File's new content.
$data = file_get_contents($newFileName);
$additionalParams = array(
'newRevision' => $newRevision,
'data' => $data,
'mimeType' => $newMimeType
);
// Send the request to the API.
$updatedFile = $service->files->update($fileId, $file, $additionalParams);
return $updatedFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
....
$data = retrieveAllFiles($service);
$fileName = 'test.txt';
$mimeType = mime_content_type('./'.$fileName);
$res = updateFile($service, $data[0]['id'], $data[0]['title'], 'update', $mimeType, $fileName, true);
I'm trying to add a text file line "test string". Function updates the data file (description, lastModifyingUser...), but the content of the file remains the same. Who can tell what's wrong?
In additionalParams need to add :
'uploadType' => 'multipart',
or
'uploadType' => 'media',
Hope it helps!
Can anyone please tell me how to store images in an oracle database as BLOBs using PHP?
A working example would be nice. Thankyou.
You first need to get the image that is being uploaded from the $_FILES #global array:
$image = file_get_contents($_FILES['image_field_name']['tmp_name']);
Then to insert the image in the database try this:
$sql = "INSERT INTO table (id, image) VALUES(1, empty_blob()) RETURNING image INTO :image";
$result = oci_parse($connection, $sql);
$blob = oci_new_descriptor($connection, OCI_D_LOB);
oci_bind_by_name($result, ":image", $blob, -1, OCI_B_BLOB);
oci_execute($result, OCI_DEFAULT) or die ("Unable to execute query");
if(!$blob->save($image)) {
oci_rollback($connection);
}
else {
oci_commit($connection);
}
oci_free_statement($result);
$blob->free();
Thank you DRiFTy, I build my small JSON query on your example.
Let's clarrify that you can save large images with both examples.
<?php
// Database parameters
$oci_user = 'YOUR_DB_USER';
$oci_pw = 'YOUR_DB_PASSWORD';
$oci_db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = 000.000.000.000)(PORT = 1521)))(CONNECT_DATA=(SID=XXX)))";
// Get data from JSON imput
$data = json_decode(file_get_contents("php://input"),true);
// Now you can do some checks on date etc.
$img = $data['IMAGE'];
$jfid = $data['OBJECT_ID'];
$jfdate = $data['DATE'];
// Let's beginn with the blob upload
// We have 3 fiels in our table: OBJECT_ID,DATE,BLOBIMAGE
// First you fill your BLOB with an 'Empty' one and assign in PL/SQL style :img
$sql = "INSERT INTO ZAEHLER.METERAPP_BILD (OBJECT_ID,DATE,BLOBIMAGE)
VALUES (".$jfid.",to_date('".$jfdate."','DD/MM/YYYY'),empty_blob())
RETURNING BLOBIMAGE INTO :img";
$result = oci_parse($conn, $sql);
$blob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($result, ":img", $blob, -1, OCI_B_BLOB);
oci_execute($result, OCI_NO_AUTO_COMMIT);
// Now let's check if we could connect to database or if we have to output something => 500
if(!$result){
$err = oci_error();
header('HTTP/1.0 500 Internal Server Error');
header('Content-Type: application/json');
$out = array('code' => '500', 'response' => '500 Internal Server Error / SQL connection problem', 'error sql' => $err[message]);
echo json_encode($out);
}
// Can we same the image ($img) or not => 406
// This step saves the image to the db
if(!$blob->save($img)) {
oci_rollback($conn);
header('HTTP/1.0 406 Not Acceptable');
header('Content-Type: application/json');
$out = array('code' => '406', 'response' => '406 Not Acceptable / Wrong image type or JSON error');
echo json_encode($out);
}
// If both was ok, we're going to commit and output an OK => 200
else {
oci_commit($conn);
header('HTTP/1.0 200 OK');
header('Content-Type: application/json');
$out = array('code' => '200', 'response' => '200 OK', 'response advanced' => 'Image saved', 'object_id' => $jfid, 'file date' => $jfdate);
echo json_encode($out);
}
// Clean up
oci_free_statement($result);
$blob->free();
?>
You can use PDO too:
<?php
include '../conexao_oracle.php';
$db = $pdo;
$db->beginTransaction(); // Essential!
$mimetype = 'image/jpeg';
$funcionario_id = 10;
$stmt = $db->prepare(
"INSERT INTO foto (mimetype, binario, funcionario_id) ".
"VALUES (:mimetype, EMPTY_BLOB(), :funcionario_id) ".
"RETURNING binario INTO :binario");
$stmt->bindParam(':mimetype', $mimetype);
$stmt->bindParam(':binario', $blob, PDO::PARAM_LOB);
$stmt->bindParam(':funcionario_id', $funcionario_id);
$blob = fopen('fotos/10.jpg', 'rb');
$stmt->execute();
$pdo->commit();
Okay so facebook want me to send an image stored locally on the server but i have the images stored in a BLOB in the database...
try {
$file = 'http://blaze-craft.com/matt/get.php?id=' . $lastid;
$post_data = array(
"message" => "Uploaded using the Funnymemes app!",
"source" => $file
);
$data['photo'] = $facebook->api("/me/photos", 'post', $post_data);
}
catch (FacebookApiException $e) {
}
but its not uploading... I got this code from the facebook api doc's so im not sure whats going on?
any ideas?
In order to photo upload to work you have to fix these:
Image files should be stored in filesystem (i.e. save BLOB back to
the disk)
Use # before image path in $post_data array.
For this purpose i would do something like:
try
{
$url = 'http://blaze-craft.com/matt/get.php?id=' . $lastid;
$saveas = '/images/image.jpg';
$res = #file_put_contents($saveas, file_get_contents($url));
if($res === false) throw new Exception('Cannot fetch image');
$post_data = array(
"message" => "Uploaded using the Funnymemes app!",
"source" => '#' . $saveas;
);
$data['photo'] = $facebook->api("/me/photos", 'post', $post_data);
}
catch (FacebookApiException $e) { }
catch (Exception $e) { }