I have successfully uploaded a file into Google Drive. However, I'm still not sure on how to upload it into a folder. I need to upload it into a folder structure which looks like this:
Stats
ACLLeauge
ACLSydney
Sorted
Unsorted
{Username}
{FileHere}
The {Username} field is a variable that I will pass through. The {FileHere} field is where the image needs to go. Here is my current code:
public function __construct()
{
$this->instance = new \Google_Client();
$this->instance->setApplicationName('DPStatsBot');
$this->instance->setDeveloperKey(Config::getInstance()->getDriveDeveloperKey());
$this->instance->setAuthConfigFile(Config::getInstance()->getClientSecret());
$this->instance->addScope('https://www.googleapis.com/auth/drive');
if(!file_exists(DP_STATS_BOT_DIR . '/' . Config::getInstance()->getAuthFile())) {
Printer::write('Please navigate to this URL and authenticate with Google: ' . PHP_EOL . $this->instance->createAuthUrl());
Printer::raw('Authentication Code: ');
$code = trim(fgets(STDIN));
$token = $this->instance->authenticate($code);
file_put_contents(DP_STATS_BOT_DIR . '/' . Config::getInstance()->getAuthFile(), $token);
Printer::write('Saved auth token');
$this->instance->setAccessToken($token);
}
else
{
$this->instance->setAccessToken(file_get_contents(DP_STATS_BOT_DIR . '/' . Config::getInstance()->getAuthFile()));
}
if($this->instance->isAccessTokenExpired())
{
$this->instance->refreshToken($this->instance->getRefreshToken());
file_put_contents(DP_STATS_BOT_DIR . '/' . Config::getInstance()->getAuthFile(), $this->instance->getAccessToken());
}
$this->drive_instance = new \Google_Service_Drive($this->instance);
}
public function upload($image, $dpname)
{
$file = new \Google_Service_Drive_DriveFile();
$file->setTitle($dpname . '_' . RandomString::string() . '.jpg');
$upload = $this->drive_instance->files->insert($file,
[
'data' => $image,
'mimeType' => 'image/jpg',
'uploadType' => 'media'
]);
return $upload;
}
If anyone has a suggestion please tell me!
Thanks
For this you have insert the folders in the order you wanted. So add the Stats under the Drive root folder and then add all the folders in the order you needed. For adding a folder, you need to give mimeType as 'application/vnd.google-apps.folder'. Check this link for more mimeType values. Here is an external referring link on how to insert a folder in Drive.
After adding all the required folders you can now insert the actual file under the {Username} folder. You can also refer to this page on how to insert a file in Drive.
Hope that helps!
Related
I am trying to generate a thumbnail of the PDF I upload in laravel the thumbnail should be the first page of the PDF. Right now I am manually uploading an image to make the thumbnail like this:
if (request()->has('pdf')) {
$pdfuploaded = request()->file('pdf');
$pdfname = $request->book_name . time() . '.' . $pdfuploaded->getClientOriginalExtension();
$pdfpath = public_path('/uploads/pdf');
$pdfuploaded->move($pdfpath, $pdfname);
$book->book_file = '/uploads/pdf/' . $pdfname;
$pdf = $book->book_file;
}
if (request()->has('cover')) {
$coveruploaded = request()->file('cover');
$covername = $request->book_name . time() . '.' . $coveruploaded->getClientOriginalExtension();
$coverpath = public_path('/uploads/cover');
$coveruploaded->move($coverpath, $covername);
$book->card_image = '/uploads/cover/' . $covername;
}
This can be tedious while entering many data I want to generate thumbnail automatically. I searched many answers but I am not able to find laravel specific. I tried to use ImageMagic and Ghost script but I couldn't find a solution and proper role to implement.
Sorry, can't comment yet!
You can use spatie/pdf-to-image to parse the first page as image when file is uploaded and store it in your storage and save the link in your database.
First you need to have php-imagick and ghostscript installed and configured. For issues with ghostscript installation you can refer this. Then add the package composer require spatie/pdf-to-image.
As per your code sample:
if (request()->has('pdf')) {
$pdfuploaded = request()->file('pdf');
$pdfname = $request->book_name . time() . '.' . $pdfuploaded->getClientOriginalExtension();
$pdfpath = public_path('/uploads/pdf');
$pdfuploaded->move($pdfpath, $pdfname);
$book->book_file = '/uploads/pdf/' . $pdfname;
$pdf = $book->book_file;
$pdfO = new Spatie\PdfToImage\Pdf($pdfpath . '/' . $pdfname);
$thumbnailPath = public_path('/uploads/thumbnails');
$thumbnail = $pdfO->setPage(1)
->setOutputFormat('png')
->saveImage($thumbnailPath . '/' . 'YourFileName.png');
// This is where you save the cover path to your database.
}
I have a method which is responsible for downloading a file.
$attachment = KnowledgeDatabaseAttachments::where('id', $id)->first();
if ($attachment) {
$filesPath = storage_path('app/knowledge_database_attachments');
return response()->download($filesPath . '/' . $attachment->physical_name);
}
After download, when I try to open it (this is an error message from my OS):
Could not load image '88ebb9c0-11af-11e8-b056-b1568dc848cb.jpg'.
Error interpreting JPEG image file (Not a JPEG file: starts with 0x0a 0xff)
File is saved like so:
$filesPath = storage_path('app/knowledge_database_attachments');
$physicalName = Uuid::generate() . '.' . $file->getClientOriginalExtension();
$file->move($filesPath, $physicalName);
KnowledgeDatabaseAttachments::create([
'knowledge_database_id' => $page->id,
'name' => $file->getClientOriginalName(),
'physical_name' => $physicalName
]);
File exist in that directory, and the downloaded file has correct size and name.
Funny part is that I can also create a newsletter which will include this file. When I create newsletter file is copied:
$extension = explode('.', $attachment->physical_name)[1];
$newPhysicalName = Uuid::generate() . '.' . $extension;
File::copy($attachment->getPathAttribute(), $storagePath . DIRECTORY_SEPARATOR . $newPhysicalName);
SendMailAttachments::create([
'mail_id' => $mail->id,
'filename' => $attachment->name,
'physical_name' => $newPhysicalName,
]);
And then, in the newsletter edit view I can as well download this file, with this (identical as above) method:
$attachment = SendMailAttachments::where('mail_id', $mailId)->where('filename', $attachmentName)->first();
if ($attachment) {
$filesPath = storage_path('app/sendmail_attachments');
return response()->download($filesPath . '/' . $attachment->physical_name);
}
And it works - file is correctly downloaded and I can open it.
Why I cant open file downloaded with first method?
I use Laravel 5.1 and Ubuntu 16.04 (if that matters).
EDIT
When I run file command on a downloaded file the result is data. When I run it on file in storage, the result is correct JPEG image data.
Try to add headers with response
View docs
$headers = array('Content-Type' => ' image/jpeg');
$filesPath = storage_path('app/knowledge_database_attachments');
return response()->download($filesPath,$attachment->physical_name,$headers);
Note: Symfony HttpFoundation, which manages file downloads, requires the file being downloaded to have an ASCII file name.
The problem is that I have something being output before the image stream.
Temporary solution:
$response = response()->download($filesPath . '/' . $attachment->physical_name);
ob_end_clean();
return $response;
Permanent solution:
Find whats being output and remove it.
Found this here: https://laracasts.com/discuss/channels/laravel/image-is-being-thrown-as-a-white-blank-image?page=1
what i want to do is upload files with an id and a certain name like (id_name.*) but before upload if there is a file with that name already then delete it.i am trying like this code below ! its in delete function but globe not getting the * sign for type . so, how can i do it ?
public function delete_files($emp_id,$name)
{
$gal = "../public/assets/documents/";
$File = glob($gal."/".$emp_id."_".$name.".".*);
unlink($File);
}
Your glob command is wrong. Try it with:
glob($gal . DIRECTORY_SEPARATOR . $emp_id . "_" . $name . ".*");
I write a edit function to update news's info, delete previous image from web root and insert new image:
code is below:
if(unlink($data['News']['image_url']['tmp_name'], WWW_ROOT . 'media/' . $data['News']['image_url']['name'])) //delete image from root and database
{
echo 'image deleted.....'; //success message
}
I can't delete old image and insert new image,how can i correct my function ?
Here your data can not find existing data. use this code
$data1 = $this->News->findById($newsid);
$this->request->data = $data1;
$directory = WWW_ROOT . 'media';
if(unlink($directory.DIRECTORY_SEPARATOR.$data1['News']['image_url']))
{
echo 'image deleted.....';
}
Pass filepath as first argument of unlink():
unlink(WWW_ROOT . 'media/' . $data['News']['image_url']['name'] . '/' . $data['News']['image_url']['tmp_name']);
Also make sure that you have proper permissions to perform this operation in directory containing image.
I am using CodeIgniter,
When I click submit I get redirected to a control which makes a photo album.
When that's done I need to create a map in images/albums/ so I can add photo's in there later on.
http://myproject/application/images/albums/feafa
my code:
$path = base_url() . APPPATH . 'images/albums/'. $albums->Album_en;
if(!file_exists($path))
{
mkdir($path);
}
Try using
$path = realpath(APPPATH . 'images/albums/'. $albums->Album_en);
instead of
$path = base_url() . APPPATH . 'images/albums/'. $albums->Album_en;
The base_url() is irrelevant as mkdir asks for the directory path(ABSOLUTE PATH)