I am making api's for my android app using Slim framework.But when i upload video to local server from my android app by calling api,it generates white thumbnail for video in my app.How can i get the thumbnail for the uploaded video.
My code for making api is:
$app->post('/do_upload', 'authentication', function () use ($app) {
verifyRequiredParams(array('albumId'));
global $user_id;
$response = array();
$file_path = "../uploads/$user_id/photo_gallery/thumbnails/";
if (!file_exists($file_path)) {
mkdir($file_path, 0777, true);
}
$thumbnail = $user_id . "/photo_gallery/thumbnails/";
$response = array();
if (isset($_FILES["files"])) {
$temp = explode(".", $_FILES['files']['name']);
$detectedType = $_FILES["files"]["name"];
$filetype = substr($detectedType, strpos($detectedType, ".") + 1);
$newfilename = 'shared_' . rand(1, 99999) . '.' . end($temp);
$file_path = $file_path . basename($newfilename);
$thumbnail = "$user_id/photo_gallery/thumbnails/" . $newfilename;
$filename = "$user_id/photo_gallery/thumbnails/" . $newfilename;
$mobile_thumbnail = "$user_id/photo_gallery/thumbnails/" . $newfilename;
if (move_uploaded_file($_FILES['files']['tmp_name'], $file_path)) {
}
$albumId = urldecode($app->request->post('albumId'));
$caption = urldecode($app->request->post('caption'));
$db = new DbHandler();
if (($filetype == "gif")
|| ($filetype == "png")
|| ($filetype == "jpeg")
|| ($filetype == "jpg")
|| ($filetype == "JPEG")
|| ($filetype == "PNG")
|| ($filetype == "GIF")
|| ($filetype == "JPG")
) {
$type = "image";
$result = $db->SharedImage($albumId, $user_id, $caption, $filename, $thumbnail, $mobile_thumbnail, $type);
} else {
$type = "video";
$result = $db->SharedImage($albumId, $user_id, $caption, $filename, $thumbnail, $mobile_thumbnail, $type);
}
if ($result != "null") {
while ($res = $result->fetch_assoc()) {
$response = array();
$response["id"] = $res["id"];
$response["event_id"] = $res["event_id"];
$response["album_id"] = $res["album_id"];
$response["status"] = $res["status"];
$response["filename"] = $res["filename"];
$response["contributedby_id"] = $res["contributedby_id"];
$response["guest_id"] = $res["guest_id"];
$response["thumbnail"] = $res["thumbnail"];
$response["mobile_thumbnail"] = $res["mobile_thumbnail"];
$response["order_id"] = $res["order_id"];
$response["created"] = $res["created"];
$response["updated"] = $res["updated"];
$response["title"] = $res["title"];
$response["type"] = $res["type"];
$response["caption"] = $res["caption"];
$response["taken"] = $res["taken"];
$response["copied_from"] = $res["copied_from"];
$response["media_size"] = $res["media_size"];
$response["thumbnail_size"] = $res["thumbnail_size"];
echoRespnse(200, $response);
}
} else {
$response["message"] = "response contain no data";
echoRespnse(200, $response["message"]);
}
} else {
$response ["error"] = true;
$response ["message"] = "Please select a file to upload";
echoRespnse(200, $response);
}
});
Please tell me why the thumbnail of video uploded is white and how can i get the video cover.
Using ffmpeg ,My problem was solved.Here is the code exec('ffmpeg -y -i '.$file_path.' -vcodec mjpeg -ss 00:00:01 -vframes 1 -an -s 620x440 -f rawvideo '.$image.'',$thumb_stdout, $retval);
This created a thumbnail at path $image of size 620*440.
Related
Android is uploading image from my laravel 5.7 API but the
$request->input('image') is always on empty. I also try it using postman and its working fine. can someone help me out? XD
success result using post man form-data type
if($request->hasFile('image'))
{
$image = $request->file('image');
$name = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('uploads/messenger');
$image->move($destinationPath, $name);
$path = url('')."/webservices/public/uploads/messenger/".$name;
$result=[
"image_url" => $path,
];
$succes = "1";
$successMessage = "Image uploaded";
$errorMessage = "";
}
else
{
$result = (object) array();
$succes = "0";
$successMessage = "";
$errorMessage = "Image not found";
}
use Storage Facades for storing file :
create folder inside storage/app/public/uploads/messenger : with 777 permission
run command : php artisan storage:link to symlink your storage folder content available to public folder
in your controller :
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;
use Carbon\Carbon;
public function upload_image(Request $request){
try{
// added validator for image field
$validator = Validator::make($request->all(), [
'image'=>'required|mimes:jpeg,jpg,png,gif|max:5120'
]);
if ($validator->fails()) {
$response=array('status'=>'error','result'=>0,'errors'=>implode(',',$validator->errors()->all()));
return response()->json($response, 200);
}else{
if($request->hasFile('image')){
$uniqueid=uniqid();
$original_name=$request->file('image')->getClientOriginalName();
$size=$request->file('image')->getSize();
$extension=$request->file('image')->getClientOriginalExtension();
$filename=Carbon::now()->format('Ymd').'_'.$uniqueid.'.'.$extension;
$imagepath=url('/storage/uploads/messenger/'.$filename);
$path=$request->file('image')->storeAs('public/uploads/messenger/',$filename);
$response=array('status'=>'success','result'=>1,'image'=>$imagepath);
return response()->json($response, 200);
}else{
$response=array('status'=>'error','result'=>0,'errors'=>'no image found');
return response()->json($response, 200);
}
}
}catch(\Exception $e){
$response=array('status'=>'error','result'=>0,'errors'=>'Internal Server Error');
return response()->json($response, 500);
}
}
add Content-Type : multipart/form-data header when uploding image from client side like android or postman
I am uploading an image from my android application and trying to store the image as Blob in Oracle database using PHP. I used the same technique for uploading the image in my web application which worked fine. I am trying the following code. Need some assistance. TIA
<?php
$conn = oci_connect("test_dev","test_dev","192.168.10.82:1509/testdv");
class emp{}
$image = $_POST['image'];
$name = $_POST['name'];
if (empty($name)) {
$response = new emp();
$response->success = 0;
$response->message = "Please dont empty Name.";
die(json_encode($response));
} else {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $image);
$DIGI_TYPE= $mime;
$lob = oci_new_descriptor($conn, OCI_D_LOB);
$myv = file_get_contents($image);
$imageProperties = getimageSize($image);
$lob->writeTemporary($myv, OCI_TEMP_BLOB);
$sql = "UPDATE LC_BLOCK_LIST_TECH_PERS
SET DIGI_SIGN = :DIGI_SIGN , DIGI_TYPE = :DIGI_TYPE
WHERE COM_CODE= '$name'";
$s = oci_parse($conn, $sql);
oci_bind_by_name($s, ':DIGI_TYPE', $DIGI_TYPE);
oci_bind_by_name($s, ':DIGI_SIGN', $lob, -1, OCI_B_BLOB);
oci_execute($s, OCI_NO_AUTO_COMMIT);
oci_commit($conn);
$lob->close();
`
<?php
$conn = oci_connect("DRUG_FINAL","DRUG_FINAL","192.168.10.85:1521/devdb");
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
else{
echo "connected";
}
$image = $_POST['image'];
$name = $_POST['name'];
if(isset($_POST["image"]) && isset($_POST["name"]))
{
$title = $_POST["name"];
$image = $_POST["image"];
$gambar = file_get_contents($image);
$gambar1 =file_put_contents(base64_decode($gambar1));
$query = "INSERT INTO images (TITLE, IMAGES) VALUES (:TITLE, EMPTY_BLOB()) RETURNING IMAGES INTO :IMAGES";
$parse = oci_parse($conn, $query);
$lob_a = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($parse, ":TITLE", $title);
oci_bind_by_name($parse, ":IMAGES", $lob_a, -1, OCI_B_BLOB);
oci_execute($parse, OCI_DEFAULT);
if($lob_a->save($gambar1))
{
oci_commit($conn);
$lob_a->free();
}
else
{
oci_rollback($conn);
}
}
i have some persian(utf8) words on my database for my android app and i am using json for show database information in android app.
I have following code on Databasemanager.php:
function getMusics()
{
$connection = mysqli_connect(DatabaseManager::HOST_NAME, DatabaseManager::USER_NAME, DatabaseManager::PASSWORD, DatabaseManager::DATABASE_NAME);
$sqlQuery = "SELECT * FROM musics where active = 1 order by date desc;";
$result = $connection->query($sqlQuery);
$musicsArray = array();
if ($result->num_rows > 0) {
for ($i = 0; $i < $result->num_rows; $i++) {
$musicsArray[$i] = $result->fetch_assoc();
}
}
echo json_encode($musicsArray);
}
and in GetMusic.php for get json information :
<?php
include "DatabaseManager.php";
$databaseManager = new DatabaseManager();
$databaseManager->getMusics();
but i have bellow jsons on output :
{"id":"3","name":"???","artist":"????? ????","like_count":"1","comment_count":"0","dl_link":null,"photo":"http:\/\/192.168.88.6\/musicarea\/photos\/3.jpg","active":"1","date":"2017-08-04 00:00:00"}
how can i solve it ??
on output(i just use persian language at 2 last rows):
on the app:
on php my admin:
You should set the default client charset to UTF-8. Use mysqli::set_charset OR mysqli_set_charset.
See http://de2.php.net/manual/en/mysqli.set-charset.php for more info.
You have to add the header that it tells the client the response is encoding with utf-8
header('Content-Type: text/html; charset=utf-8');
EDIT
function getMusics()
{
$connection = mysqli_connect(DatabaseManager::HOST_NAME, DatabaseManager::USER_NAME, DatabaseManager::PASSWORD, DatabaseManager::DATABASE_NAME);
$sqlQuery = "SELECT * FROM musics where active = 1 order by date desc;";
$result = $connection->query($sqlQuery);
$musicsArray = array();
if ($result->num_rows > 0) {
for ($i = 0; $i < $result->num_rows; $i++) {
$musicsArray[$i] = $result->fetch_assoc();
}
}
header("Content-type: application/json; charset=utf-8");
echo json_encode($musicsArray);
}
On our platform (based on Laravel 5.1) we provide audio and video content to registered users. The media files are stored outside the docroot of course.
So I use a method to provide the requested content. That works well on any browser and OS except Android (native or chrome). Android uses a byte range request for audio and video tags. The following code worked in the beginning and stopped working a while ago. I have no clue why. Any:
public function loadfile(Request $request, $type, $filename="")
{
$filepath = $mediadirectory . $filename;
if (File::isFile($filepath)) {
$file = File::get($filepath);
$mimetype = File::mimeType($filepath);
$size = File::size($filepath);
if ($mimetype=="audio/mpeg" || $mimetype=="video/mp4") {
$stream = fopen($filepath, "r");
$start = 0;
$length = $size;
$status = 200;
$headers = ['Content-Type' => $mimetype, 'Content-Length' => $size, 'Accept-Ranges' => 'bytes'];
if (false !== $range = $request->server('HTTP_RANGE', false)) {
list($param, $range) = explode('=', $range);
if (strtolower(trim($param)) !== 'bytes') {
header('HTTP/1.1 400 Invalid Request');
exit;
}
list($from, $to) = explode('-', $range);
if ($from === '') {
$end = $size - 1;
$start = $end - intval($from);
} elseif ($to === '') {
$start = intval($from);
$end = $size - 1;
} else {
$start = intval($from);
$end = intval($to);
}
$length = $end - $start + 1;
$status = 206;
$headers['Content-Range'] = sprintf('bytes %d-%d/%d', $start, $end, $size);
$headers['Connection'] = "keep-alive";
}
$response=new StreamedResponse(function() use ($stream, $start, $length) {
fseek($stream, $start, SEEK_SET);
echo fread($stream, $length);
fclose($stream);
}, $status, $headers);
return $response->send();
} else {
return response($file, 200)->header('Content-Type', $mimetype)->header('Content-Length', $size)->header('Content-Disposition', 'filename="' . $filename . '"');
}
}
}
The html is straight forward html5:
<audio controls preload="auto">
<source src="/loadfile/principiante.mp3" type="audio/mpeg">
</audio>
How to retrieve the ids array from the following JSON Object.
{"bets":[{"bet":[{"gid":"10","Result":null}]},{"bet":[{"gid":"7","Result":null}]},{"bet":[{"gid":"3","Result":null},{"gid":"6","Result":"2"}]},{"bet":[{"gid":"6","Result":"2"},{"gid":"4","Result":"1"}]},{"bet":[{"gid":"6","Result":"2"},{"gid":"4","Result":"1"}]}]}{"ids":["9c9nogs6of","ank4kt3gqo","jfgrt91nk4","a8qmoq7v4q","8mov5ita1t"]}
I've tried
allids = jObj.getJSONArray("ids");
which should work because it works with jObj.getJSONArray("bets"); however I receive this error in logcat E/Buffer Errorīš Error converting result org.json.JSONException: No value for ids
PHP FILE
<?php
// get tag
$param= $_POST['param'];
$bet = explode("//",$param);
$allbetslength = count($bet);
$ultresponse["bets"] = array();
$idresponse["ids"] = array();
for ($x = 0; $x < $allbetslength; $x++) {
$indid = substr($bet[$x],0,10);
array_push($idresponse["ids"], $indid);
$bet[$x] = substr($bet[$x],10);
$id = explode(",",$bet[$x]);
$arrlength = count($id);
// include db handler
require_once 'include/Check_Bets.php';
$db = new Check_Bets();
$response["bet"] = array();
for($y = 0; $y < $arrlength; $y++) {
$result= $db->checkuserbets($id[$y]);
array_push($response["bet"], $result);
}
array_push($ultresponse["bets"], $response);
array_push($ultresponse["bets"], $idresponse["ids"]);
}
echo json_encode($ultresponse);
?>