Cannot upload .doc file with google drive sdk - php

I can upload .docx file to google drive from my apps, but when i tried to upload .doc file, this error appeared :
An error occurred: Error calling POST https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart&key=AIzaSyCm1WqPp05lBRjKSpxdtHjS8lz6WLeoWlU: (400) Invalid mime type provided
That error appeared too when I uploaded .ppt .xls file. The documentation says we can store any MIME type in Google Drive. What's wrong here? Anybody knows?
This is my upload function :
function insertFile($title, $description, $parentId, $mimeType, $filename) {
$file = new DriveFile();
$file->setTitle($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
if ($parentId != null) {
$parent = new ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));
}
try {
$data = file_get_contents($filename);
$createdFile = $this->service->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
));
return $createdFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
[UPDATE] I'm using CI and this is my function in controller that calls insertFile function :
function upload() {
$title = $this->input->post('title');
$description = $this->input->post('description');
$parentId = $this->input->post('parentId');
if ($_FILES["file"]["error"] > 0) {
echo "Error: " . $_FILES["file"]["error"] . "<br>";
} else {
$driveHandler = new DriveHandler($_SESSION['credentials']);
$driveHandler->BuildService($_SESSION['credentials']);
$ext = substr(strrchr($_FILES["file"]["name"],'.'),1);
if($title === ""){
$fileTitle = $_FILES["file"]["name"];
} else {
$fileTitle = "$title.$ext";
}
$driveHandler->insertFile($fileTitle, $description, $parentId, $_FILES["file"]["type"], $_FILES["file"]["tmp_name"]);
}

When I try to use var_dump($mimeType) for .docx file, the result is :
string(71) "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
and for .doc file :
string(20) ""application/msword""
Based on the results, I found the problem. There is an additional double quote in $mimeType for .doc file. So I try to change my code like this :
$data = file_get_contents($filename);
$mime = str_replace('"', "", $mimeType);
$createdFile = $this->service->files->insert($file, array(
'data' => $data,
'mimeType' => $mime,
));
It now works.

Rather than just replacing double quotes, you can use a negative character class in regular expression with preg_replace() to replace any non alphanumeric, /, or . characters.
$mimeType = preg_replace("~[^a-zA-Z0-9/\.]*~", "", $mimeType);

Related

[PHP][SLIM] move_uploaded_file never ends with larger files in Hosting24

I have a question.
I'm trying to upload files to a server, this server is hosted by 'Hosting24', i don't know if that matters, anyway, if I try to move files larger than 70mb It never ends to load and never send a response, my server config is okay, it has these values: {"post_max_size":"512M","memory_limit":"1024M"}
I has tryed with $_FILES and ftp transfer and it doesnt works, it never ends of load.
I'm using Slim framework and this is the function:
public function testCode($request, $response, $args)
{
$data = $request->getParsedBody();
$uploadedFiles = $request->getUploadedFiles();
//here take files
$uploadedFile = $uploadedFiles['file_user'];
$nameC = $data['nombre_curso'];
//here set path
$path = "../../scorm/temp/" . $nameC . '/';
//Creating folders
if (!#mkdir($path, 0777, true)) {
$error = error_get_last();
echo $error['message'];
}
$file_name = $uploadedFile->getClientFilename();
$array = explode(".", $file_name);
$ext = $array[1];
//if is a zip file
if ($ext == 'zip') {
$location = $path . "/" . $file_name;
//here move the uploaded file to my selected directory
if (move_uploaded_file($uploadedFile->file, $location)) {
$obj = (object) array("response" => 'works', 'post_max_size' => ini_get('post_max_size'), 'memory_limit' => ini_get('memory_limit'));
$response->withStatus(200);
$response->getBody()->write(json_encode($obj));
return $response;
} else {
$error = error_get_last();
echo $error['message'] . " it couldn't be moved";
}
} else {
echo "no zip";
}
}

symfony post api is taking too much time to load

I have a api, which will upload the images of the users to server.
It will take the images in base64 format and send that to server. But the problem is for some user it will take long time, and for some user it works well.
I am not getting why this is happening. But the destination directory is a having 700GB of data.
code for uploading :
`
$file will be having base64 format of image
$this->file = $file;
if ($this->id && !empty($this->path) && !is_null($file)) {
$this->storeFilenameForRemove();
}
if ($file instanceof File) {
if (isset($this->path)) {
$this->temp = $this->path;
$this->path = null;
} else {
$this->path = 'initial';
}
} else if (gettype($file) == 'string') {
if (preg_match('/data:(\w+)\/(\w+);base64,/i', $file, $matches)) {
if ($matches) {
$file = preg_replace('/data:(\w+)\/(\w+);base64,/i', '', $file);
$tmpFile = Array();
$tmpFile['data'] = base64_decode( str_replace(' ', '+', $file) );
if ($matches[1] === 'image') {
$tmpFile['name'] = uniqid().'.png';
} else {
$tmpFile['name'] = uniqid().'.'.$matches[2];
}
$tmpFile['handle'] = fopen( $this->getUploadRootDir().'/'.$tmpFile['name'], 'w' );
// inject the raw image data into the new file
fwrite( $tmpFile['handle'], $tmpFile['data'] );
fclose( $tmpFile['handle'] );
$this->path = $tmpFile['name'];
}
}
} else {
$this->file = $file;
}`
I'm not sure if executing a preg_match on a base64 encoded string is a good idea, while I'm not sure that fixes all of your problems regarding speed I'm positive that implementing a different check for base64 encoded strings would improve the speed.
Replace the following:
if (preg_match('/data:(\w+)\/(\w+);base64,/i', $file, $matches)) {
with this
if ( base64_encode(base64_decode($file)) === $file){

zip folder and download in codeigniter

public function folderdownload(){
try{
$this->load->library('zip');
$this->load->helper('file');
$where = array(
'file_perm_id'=>$this->input->post('id'));
$this->load->model('fetch_model');
$file_path = $this->fetch_model->getalldata($this->folderpath,$this->master,$where);
$path = ##$file_path[0]->folder_path ;
$files = get_filenames($path);
// when i used print_r($files); to verify that i can see the files i can see it from here
foreach($files as $f){
if (is_file($path . $f))
$this->zip->add_data($f, file_get_contents($path . $f));
}
ob_end_clean();
$this->zip->download(date('m-d-Y'));
}catch(Exception $e){
echo 'Caught exception: ', $e->getMessage(), "\n";
}
}
I have this controller that once the use click the download button it download all the files within the folder but when I open it it says that the archieve is either unknown format or damaged. please help hoiw can I download files and zip it this is in codeigniter. thanks anyone
public function folderdownload(){
try{
$this->load->library('zip');
$this->load->helper('file');
$where = array(
'file_perm_id'=>$this->input->get('id'));
$this->load->model('fetch_model');
$file_path = $this->fetch_model->getalldata($this->folderpath,$this->master,$where);
$path =$file_path[0]->folder_path ;
$finallink = ($_SERVER['DOCUMENT_ROOT'] . "/cobacfms/" . $path);
$this->zip->read_dir(($finallink), false);
$this->zip->download(date('m-d-Y'));
}catch(Exception $e){
echo 'Caught exception: ', $e->getMessage(), "\n";
}
}
This is the solution to my problem
Your zip file creation is having issue.
I would suggest you to first check you content availability and then create zip file and at last download it.
To create ZIP file
$sourcePath = 'uploads/sourceDirectory';
$targetPath = 'uploads/destDirectory';
if (file_exists($sourcePath)){
if(!copy($sourcePath, $targetPath)){ //Copy file source to destination directory
return ['status' => false, 'msg' => 'File missing'];
}
}
if (file_exists($targetPath)){ // check target directory
$this->zip->read_dir($targetPath,False); // read target directory
if(!$this->zip->archive($targetPath.'.zip')){ // zip target directory
return ['status' => false, 'msg' => 'Zip file creation Failed!'];
}else{
return ['status' => false, 'msg' => 'Zip file Created'];
}
}

file not found exception in laravel

I am facing some problem while uploading image in laravel framework of my project .I checked image is uploading to folder , but still this error is coming
Below is coding
/////////// Course Image ///////////
$tmp_name1 = $course_image['tmp_name'];
$type1 = $course_image['type'];
$name1 = $course_image['name'];
$res1 = $this->upload_file($tmp_name1, $name1);
if ($res1) {
$course_image_url = $res1;
} else {
$course_image_url = "";
}
function upload_file($source, $name) {
$list = explode(".", $name);
$ext = $list[count($list) - 1];
$ext = strtolower($ext);
if (in_array($ext, $this->file_extension)) {
$filename = md5(date("YmdHis") . microtime() . rand(100, 100000000)) . "." . $ext;
$destination = "public/uploads/" . $filename;
$res = move_uploaded_file($source, $destination);
if ($res) {
return $destination = "uploads/" . $filename;
} else {
$message = "Internal server error";
(json_encode(array("responseCode" => "500", "responseMsg" => array("status" => "error", "statusReason" => $message))));
}
} else {
$message = "Invalid file extention";
(json_encode(array("responseCode" => "500", "responseMsg" => array("status" => "error", "statusReason" => $message))));
}
}
There are lots of codes , I posted only the required one .
You should follow the Laravel Example for Uploading Files.
I.e., you can check if a file has been uploaded successfully using:
if ($request->hasFile('image')) {
//
}
And you can move / rename a file using:
$request->file('image')->move($destinationPath);
or
$request->file('image')->move($destinationPath, $fileName);
I found that issue .
Go to line number 66 of this path(D:\xampp\htdocs\blog\vendor\laravel\framework\src\Illuminate\Http\UploadedFile.php) in your project folder .or search the text instanceof static.
After it remove the "instanceof static" ,then it is working fine.
Thanx

Laravel: Save Base64 .png file to public folder from controller

I send a png image file to controller in base64 via Ajax. I've already test and sure that controller has received id but still can't save it to public folder.
Here is my controller
public function postTest() {
$data = Input::all();
//get the base-64 from data
$base64_str = substr($data->base64_image, strpos($data->base64_image, ",")+1);
//decode base64 string
$image = base64_decode($base64_str);
$png_url = "product-".time().".png";
$path = public_path('img/designs/' . $png_url);
Image::make($image->getRealPath())->save($path);
// I've tried using
// $result = file_put_contents($path, $image);
// too but still not working
$response = array(
'status' => 'success',
);
return Response::json( $response );
}
Intervention Image gets binary data using file_get_content function:
Reference : Image::make
Your controller should be look like this:
public function postTest() {
$data = Input::all();
$png_url = "product-".time().".png";
$path = public_path().'img/designs/' . $png_url;
Image::make(file_get_contents($data->base64_image))->save($path);
$response = array(
'status' => 'success',
);
return Response::json( $response );
}
$data = Input::all();
$png_url = "perfil-".time().".jpg";
$path = public_path() . "/img/designs/" . $png_url;
$img = $data['fileo'];
$img = substr($img, strpos($img, ",")+1);
$data = base64_decode($img);
$success = file_put_contents($path, $data);
print $success ? $png_url : 'Unable to save the file.';
$file = base64_decode($request['image']);
$safeName = str_random(10).'.'.'png';
$success = file_put_contents(public_path().'/uploads/'.$safeName, $file);
print $success;
This is an easy mistake.
You are using public_path incorrectly. It should be:
$path = public_path() . "/img/designs/" . $png_url;
Also, I would avoid your method of sending the image. Look at a proper upload in a form and use Laravel's Input::file method.
My solution is:
public function postTest() {
$data = Input::all();
//get the base-64 from data
$base64_str = substr($data->base64_image, strpos($data->base64_image, ",")+1);
//decode base64 string
$image = base64_decode($base64_str);
Storage::disk('local')->put('imgage.png', $image);
$storagePath = Storage::disk('local')->getDriver()->getAdapter()->getPathPrefix();
echo $storagePath.'imgage.png';
$response = array(
'status' => 'success',
);
return Response::json( $response );
}
what am i doing is using basic way
$file = base64_decode($request['profile_pic']);
$folderName = '/uploads/users/';
$safeName = str_random(10).'.'.'png';
$destinationPath = public_path() . $folderName;
file_put_contents(public_path().'/uploads/users/'.$safeName, $file);
//save new file path into db
$userObj->profile_pic = $safeName;
}
Store or save base64 images in the public folder image and return file path.
$folderPath = public_path() . '/' . 'images/';
$image_parts = explode(";base64,", $image);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$uniqid = uniqid();
$file = $folderPath . $uniqid . '.' . $image_type;
file_put_contents($file, $image_base64);
return $file;
Actually, Input::all() returns an array of inputs so you have following:
$data = Input::all();
Now your $data is an array not an object so you are trying to access the image as an object like:
$data->base64_image
So, it's not working. You should try using:
$image = $data['base64_image'];
Since it's (base64_image) accessible from $_POST then Input::file('base64_image') won't work because Input::file('base64_image') checks the $_FILES array and it's not there in your case.
Here is my solution for the file upload from base_64.
public static function uploadBase64File(Request $request, $requestName = 'imageData', $fileName = null, $uploadPath = 'uploads/images/')
{
try {
$requestFileData = $request->$requestName;
// decode the base64 file
$file = base64_decode(preg_replace(
'#^data:([^;]+);base64,#',
'',
$request->input($requestName)
));
if (in_array($file, ["", null, ' '])) {
return null;
}
//handle base64 encoded images here
if ($fileName == null) {
$fileName = Str::random(10);
}
$extension = '.' . explode('/', explode(':', substr($requestFileData, 0, strpos($requestFileData, ';')))[1])[1];
$filePath = $uploadPath . '' . $fileName . '' . $extension;
// dd($extension);
if (!File::exists(public_path($uploadPath))) {
File::makeDirectory(public_path($uploadPath), 0777, true);
}
// dd($filePath);
$ifImageUploadSuccessful = File::put(public_path($filePath), $file);
if (!$ifImageUploadSuccessful) {
return null;
}
return '/' . $filePath;
// throw new Exception("Unable To upload Image");
} catch (Exception $e) {
// dd($e);
throw new Exception($e->getMessage());
}
}
I'v done it!!
I replaced
$data->base64_image to $_POST['base64_image'] and then use
$result = file_put_contents($path, $image);
instead of Image::make($image->getRealPath())->save($path);
But this doesn't look like a laravel ways. I you have another way that look more elegant please tell me!

Categories