add folder to folder using google drive API - google-drive-api

The script below is creating folders within a parent folder using
"google drive API". It works perfectly however, after a while (20 folders or so) it is not working anymore.
No error message just no more folder creation within the parent folder.
It goes somewhere else!
To enable that creation a "service account" was created and parent folder is share between "personal google account" and "service account"
Can someone provide help please?
php function send_google_drive($id,$fileno,$filename1,$filename2){
global $wpdb;
require(ABSPATH.'/wp-content/themes/enemat/googledrives/vendor/autoload.php');
$client = getClient();
$service = new Google_Service_Drive($client);
if(!empty($filename1)){
$results = $service->files->listFiles();
foreach ($results->getFiles() as $item) {
if ($item['name'] == 'ENEMAT CRM FILES') {
$folderId = $item['id'];
break;
}
}
$parentid = $folderId;
$childid = "";
foreach ($results->getFiles() as $item) {
if ($item['name'] == $fileno) {
$childid = $item['id'];
break;
}
}
if(empty($childid)){
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => $fileno,
'parents'=>array($parentid),
'mimeType' => 'application/vnd.google-apps.folder'));
$file = $service->files->create($fileMetadata, array(
'fields' => 'id'));
$folderId = $file->id;
}else{
$folderId = $childid;
}
$newPermission = new Google_Service_Drive_Permission();
$newPermission->setType('anyone');
$newPermission->setRole('reader');
$service->permissions->create($folderId, $newPermission);
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => array(basename($filename1)),
'parents' => array($folderId)
));
$content = file_get_contents($filename1);
$files = $service->files->create($fileMetadata, array(
'data' => $content,
'uploadType' => 'resumable',
'fields' => 'id'));
$fileids = $files->id;
$docusignorgs = "https://drive.google.com/open?id=".$fileids."";
$folderslink = "https://drive.google.com/drive/folders/".$folderId."";
#unlink(ABSPATH."wp-content/themes/enemat/pdfs/".basename($filename1));
$newPermission = new Google_Service_Drive_Permission();
$newPermission->setType('anyone');
$newPermission->setRole('reader');
$service->permissions->create($fileids, $newPermission);
}
if(!empty($filename2)){
$results = $service->files->listFiles();
foreach ($results->getFiles() as $item) {
if ($item['name'] == '46 - CONTRAT PARTENARIAT') {
$folderId = $item['id'];
break;
}
}
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => array(basename($filename2)),
'parents' => array($folderId)
));
$content = file_get_contents($filename2);
$files = $service->files->create($fileMetadata, array(
'data' => $content,
'uploadType' => 'resumable',
'fields' => 'id'));
$fileids1 = $files->id;
$contractdrivelink = "https://drive.google.com/open?id=".$fileids1."";
$newPermission = new Google_Service_Drive_Permission();
$newPermission->setType('anyone');
$newPermission->setRole('reader');
$service->permissions->create($fileids1, $newPermission);
}
}
?

The reason there is no error message is because your code has no error handling! If GDrive fails to do something, it returns an error code and message to explain why. Your code should be catching that error and displaying it.
My guess is that you are hitting a rate limit. To see if this is the cause or not, add a 2 second delay between each folder creation. If it no runs correctly, you know that rate limiting is your problem.

Related

Google Drive API can't set permissions with reusable upload

When I did a basic file upload & set the permission like so, it worked great:
$file = $service->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => $mimeType,
'uploadType' => 'multipart',
'fields' => 'id'));
$permissions = new Google_Service_Drive_Permission(array(
"role" => "reader",
"type" => "anyone",
));
$setPermission = $service->permissions->create($file->id, $permissions);
But when I upload a large file that's split into chunks & use the resumable uploadType, the permissions aren't set on the file & I don't get any errors:
$service = new Google_Service_Drive($client);
$file = new Google_Service_Drive_DriveFile();
$file->title = $fileName;
$file->name = $fileName;
$chunkSizeBytes = 1 * 1024 * 1024;
$mimeType = mime_content_type($fullpath);
// Call the API with the media upload, defer so it doesn't immediately return.
$client->setDefer(true);
$request = $service->files->create($file);
// Create a media file upload to represent our upload process.
$media = new Google_Http_MediaFileUpload(
$client,
$request,
$mimeType,
null,
true,
$chunkSizeBytes
);
$media->setFileSize(filesize($fullpath));
// Upload the various chunks. $status will be false until the process is complete.
$status = false;
$handle = fopen($fullpath, "rb");
while (!$status && !feof($handle)) {
$chunk = fread($handle, $chunkSizeBytes);
$status = $media->nextChunk($chunk);
}
// The final value of $status will be the data from the API for the object that has been uploaded.
$result = false;
if($status != false) {
$result = $status;
error_log($result->id);
}
fclose($handle);
$permissions = new Google_Service_Drive_Permission(array(
"role" => "reader",
"type" => "anyone"
));
$setPermission = $service->permissions->create($result->id, $permissions);
Any suggestions on what I'm doing wrong?
I have had the same situation with you. In that case, when the file information is retrieved with $res = $service->files->get($result->id); after the file was uploaded with the resumable upload, the empty object of {} is returned without error. I thought that this is the reason of the issue.
So, I used the following workaround. In this workaround, after the file was uploaded with the resumable upload, I retrieved $client again. By this, $res = $service->files->get($result->id); worked after the file was uploaded. When this is used for your script, please modify as follows.
From:
fclose($handle);
$permissions = new Google_Service_Drive_Permission(array(
"role" => "reader",
"type" => "anyone"
));
$setPermission = $service->permissions->create($result->id, $permissions);
To:
fclose($handle);
$client = getClient(); // <--- Added
$service = new Google_Service_Drive($client); // <--- Added
$permissions = new Google_Service_Drive_Permission(array(
"role" => "reader",
"type" => "anyone"
));
$setPermission = $service->permissions->create($result->id, $permissions);
getClient() is for retrieving $client. So please modify this part for your actual situation.
Note:
This answer supposes that your $client can be created the permissions to the uploaded file. Please be careful this.
$client->setDefer(true); is causing the issue. That's why it works when you create a new instance of Google client.
Another fix might be to do $client->setDefer(false); after uploading the file.

API Create Multiple Input Laravel

I'm currently creating API for multiple inputs using laravel. The data will be stored into two tables : Order and Detail_Order. One order can have many detail orders.
But now, the data only stored into Order table, and got an error: ErrorException: Invalid argument supplied for foreach() in file. Does anyone know how? Thank you.
Here's my code :
public function createDetail($total_passenger, $id_trip, $id_users, Request $request){
$trip = Trip::where(['id_trip' => $id_trip])->get();
$seat = $request->id_seat;
if(Detail_Order::where(['id_trip' => $id_trip, 'id_seat' => $seat])
->where('status', '!=', 5)
->exists()) {
return $this->error("Seat has been booked");
}else{
$order = new Order();
$order_select = Order::select('id_order');
$order_count = $order_select->count();
if ($order_count === 0) {
$order->id_order = 'P1';
}else{
$lastrow=$order_select->orderBy('created_at','desc')->first();
$lastrow_id = explode('P', $lastrow->id_order);
$new_id = $lastrow_id[1]+1;
$order->id_order = 'P'.$new_id;
}
$order->id_trip = $id_trip;
$order->id_users = $id_users;
$order->date_order = date('Y-m-d H:i:s');
$order->id_users_operator = 'O4';
$order->save();
foreach($request->passenger_name as $key => $value){
Detail_Order::create([
'id_trip' => $order->id_trip,
'id_seat' => $request->id_seat[$key],
'id_order' => $order->id_order,
'passenger_name' => $request->passenger_name[$key],
'gender' => $request->gender[$key],
'departure' => $request->departure[$key],
'destination' => $request->destination[$key],
'phone' => $request->phone[$key],
'status' => 1
]);
}
return response()->json([
'status' => true,
'message' => "Successfully saved data",
'data' => $order
]);
}

image not insert in mysql using codeigniter

I am trying to insert images in mysql database with other data but its shows error.
its shows the $msg of not saved & repeat data of view file maybe due to $error which i set.
PS: I set 'image' datatype varchar in database.
here is my view file:
<input type="file" class="form-control-file" name="image" id="exampleInputFile" >
this is my controller:
public function save()
{
$this->load->model('Partner_model');
$feature = $this->input->post('feature');
$config['upload_path'] = './uploads/files';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('image'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('partner_profile', $error);
}
else
{
$user_data= array(
'pname' => $this->input->post('pname'),
'type' => $this->input->post('type'),
'address' => $this->input->post('address'),
'about' => $this->input->post('about'),
'city' => $this->input->post('city'),
'code' => $this->input->post('code'),
'state'=>$this->input->post('state'),
// 'image'=>$this->upload->do_upload('image')
'feature'=>implode(",",$feature),
'image' => $this->upload->data()
);
}
if($this->Partner_model->save($user_data))
{
$msg = "save sucesss" ;
}
else
{
$msg = "not save";
}
$this->session->set_flashdata('msg', $msg);
$this->load->view('partner_profile');
}
}
& this is my model:
public function save($data)
{
return $this->db->insert('property', $data);
}
Your form must have the multipart attribute in HTML file like below :
If you're using form helper, then it should be
<?php echo form_open_multipart('/save');?>
Else your form should have the enctype attribute like below
<form enctype="multipart/form-data">
Then the uploaded data result $this->upload->data() will come in array. So you can't store your array in mysql column. So you need to get the filename from $this->upload->data() and store it in a variable like below.
Your Controller should be
public function save(){
$this->load->model('Partner_model');
$feature = $this->input->post('feature');
$config['upload_path'] = './uploads/files';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('image')){
$error = array('error' => $this->upload->display_errors());
$this->load->view('partner_profile', $error);
}else{
$imageArray = $this->upload->data();
$image = $imageArray['file_name'];
$user_data= array(
'pname' => $this->input->post('pname'),
'type' => $this->input->post('type'),
'address' => $this->input->post('address'),
'about' => $this->input->post('about'),
'city' => $this->input->post('city'),
'code' => $this->input->post('code'),
'state'=>$this->input->post('state'),
'feature'=>implode(",",$feature),
'image' => $image
);
}
if($this->Partner_model->save($user_data)) {
$msg = "save sucesss" ;
}else {
$msg = "not save";
}
$this->session->set_flashdata('msg', $msg);
$this->load->view('partner_profile');
}

How to update multiple images in kartik Upload widget?

Here i can only able preview the images on update the model. I want to load the images properly so user can remove one r more file and update will work accordingly Here is my controller
public function actionUpdate($id)
{
$model = $this->findModel($id);
$session_data = \common\models\Customer::find()->where(['user_id' => $model->customer_user_id])->one();
$towing = \common\models\TowingRequest::find()->where(['id' => $model->towing_request_id])->one();
$images_old = \common\models\Images::find()->where(['=', 'vehicle_id', $model->id])->all();
$images = \common\models\Images::find()->where(['=', 'vehicle_id', $model->id])->one();
if (!$images) {
$images = new \common\models\Images();
}
if ($images_old) {
foreach ($images_old as $image) {
$baseurl = \Yii::$app->request->BaseUrl;
$image_url = $baseurl . '../backend/uploads/' . $image->thumbnail;
$all_images[] = Html::img("$image_url", ['class' => 'file-preview-image']);
}
} else {
$all_images = '';
}
$vehiclefeatures = new \common\models\VehicleFeatures();
$vehiclecondition = new \common\models\VehicleCondition();
$featuredata = \common\models\VehicleFeatures::find()->where(['=', 'vehicle_id', $model->id])->all();
$conditiondata = \common\models\VehicleCondition::find()->where(['=', 'vehicle_id', $model->id])->all();
$features = \common\models\Features::find()->all();
// $vf = Yii::$app->db->createCommand('SELECT * FROM features f left join vehicle_features vf on vf.features_id=f.id;')->queryAll();
$condition = \common\models\Condition::find()->all();
if ($model->load(Yii::$app->request->post()) && $towing->load(Yii::$app->request->post()) && $vehiclefeatures->load(Yii::$app->request->post()) && $vehiclecondition->load(Yii::$app->request->post()) && $images->load(Yii::$app->request->post())) {
$towing->save();
if (!$model->save()) {
$result = [];
// The code below comes from ActiveForm::validate(). We do not need to validate the model
// again, as it was already validated by save(). Just collect the messages.
foreach ($model->getErrors() as $attribute => $errors) {
$result[Html::getInputId($model, $attribute)] = $errors;
}
return $this->asJson(['validation' => $result]);
// Yii::$app->response->statusCode = 422;
}
//delet vehicle features and add new features
$command = Yii::$app->db->createCommand()
->delete('vehicle_features', 'vehicle_id = ' . $model->id)
->execute();
if ($vehiclefeatures->value) {
$vehicle_feature = \common\models\VehicleFeatures::inert_vehicle_feature($model, $vehiclefeatures->value);
}
//delete vehicle condition and add new features
$command = Yii::$app->db->createCommand()
->delete('vehicle_condition', 'vehicle_id = ' . $model->id)
->execute();
if ($vehiclecondition->value) {
$vehicle_condition = \common\models\VehicleCondition::inert_vehicle_condition($model, $vehiclecondition->value);
}
$photo = UploadedFile::getInstances($images, 'name');
if ($photo) {
$command = Yii::$app->db->createCommand()
->delete('images', 'vehicle_id = ' . $model->id)
->execute();
$save_images = \common\models\Images::save_container_images($model->id, $photo);
}
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('update', [
'model' => $model,
'towing' => $towing,
'images' => $images,
'features' => $features,
'condition' => $condition,
'vehiclefeatures' => $vehiclefeatures,
'vehiclecondition' => $vehiclecondition,
'all_images' => $all_images,
'featuredata' => $featuredata,
'conditiondata' => $conditiondata,
'session_data' => $session_data,
]);
}
And here is my form where I have an issue on update the images. I know here I am just previewing the image by adding it in $all_images[] in the controller and initialPreview => $all_images in form to just show it on upload. Now I want exactly is to load the images properly so I can remove any image and can able to add more images. I just want here is how to load all the images properly in the upload widget on update After uploading it properly on update i can process it on the controller that i will delete and unlink all images and uploading the updating files
Here is my form with model images
<?=
$form->field($images, 'name[]')->widget(FileInput::classname(), [
'options' => ['accept' => 'image/*', 'multiple' => true],
'pluginOptions' => [
'previewFileType' => 'image',
'allowedFileExtensions' => ['jpg', 'gif', 'png', 'bmp','jpeg'],
'showUpload' => true,
'initialPreview' => $all_images,
'overwriteInitial' => true,
],
]);
?>
Yii2 Fileinput Upload Multiple Images, AJAX based Images Previews and Delete Images.
Please Refer For Multiple Images : https://stackoverflow.com/a/53832224/2218492
Table : products_images
id (Primary)
product_id (FK)
image
Table : product
id (Primary)
Name
ect
Here View Forms...
<?php
use yii\helpers\Html;
use yii\helpers\Url;
use kartik\widgets\FileInput;
?>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?php echo '<label class="control-label">Choose an Image file(.png, .jpg)</label>'; ?>
<?php
//For Update Form : Fetch Uploaded Images and create Array to preview
$imagesList = array();
$imagesListId = array();
foreach ($model->productsImages as $img) {
$imagesList[] = Url::base(TRUE) . '/' . $img->image;
$imagesListId[]['key'] = $img->id;
}
?>
<?php
$empty_image = Url::base(TRUE) . "/uploads/image-upload-empty.png";
echo FileInput::widget([
'model' => $model,
'attribute' => 'products_image[]',
'name' => 'products_image[]',
'options' => ['multiple' => true, 'accept' => 'image/*', 'id' => 'products_image_id'],
'pluginOptions' => [
'initialPreview' => $imagesList,
'initialPreviewConfig' => $imagesListId,
'deleteUrl' => Url::to(['products/delete-image']),
'showCaption' => false,
'showRemove' => false,
'showUpload' => false,
'browseClass' => 'btn btn-primary col-lg-6 col-md-8 col-sm-8 col-xs-6',
'browseIcon' => '<i class="glyphicon glyphicon-plus-sign"></i> ',
'browseLabel' => 'Upload Image',
'allowedFileExtensions' => ['jpg', 'png'],
'previewFileType' => ['jpg', 'png'],
'initialPreviewAsData' => true,
'overwriteInitial' => false,
"uploadUrl" => Url::to(['products/upload']),
'uploadExtraData' => ['products_id' => $model->id, 'is_post' => $model->isNewRecord ? 'new' : 'update'],
'msgUploadBegin' => Yii::t('app', 'Please wait, system is uploading the files'),
//'msgUploadThreshold' => Yii::t('app', 'Please wait, system is uploading the files'),
//'msgUploadEnd' => Yii::t('app', 'Done'),
'msgFilesTooMany' => 'Maximum 15 products Images are allowed to be uploaded.',
'dropZoneClickTitle' => '',
"uploadAsync" => true,
"browseOnZoneClick" => true,
"dropZoneTitle" => '<img src=' . $empty_image . ' />',
'fileActionSettings' => [
'showZoom' => true,
'showRemove' => true,
'showUpload' => false,
],
'validateInitialCount' => true,
'maxFileCount' => 15,
'maxFileSize' => 5120, //5mb
'msgPlaceholder' => 'Select attachments',
],
'pluginEvents' => [
'filebatchselected' => 'function(event, files) {
$(this).fileinput("upload");
}',
/* 'uploadExtraData' => 'function() {
var out = {}, key, i = 0;
$(".kv-input:visible").each(function() {
$el = $(this);
key = $el.hasClass("kv-new") ? "new_" + i : "init_" + i;
out[key] = $el.val();
i++;
});
return out;
}', */
'filepredelete' => 'function(event, files) {
//var abort = true;
var index = uploaded_images.indexOf(files);
if (index !== -1) uploaded_images.splice(index, 1);
console.log(uploaded_images);
$("#productsmaster-images_array").val(uploaded_images);
//return abort;
}',
'fileuploaded' => 'function(event, data, previewId, index){
//alert( data.response.initialPreviewConfig[0].key);
uploaded_images.push(data.response.initialPreviewConfig[0].key);
console.log(uploaded_images);
$("#productsmaster-images_array").val(uploaded_images);
}',
/* 'filepreupload' => 'function(event, data, previewId, index){
var form = data.form, files = data.files, extra = data.extra,
response = data.response, reader = data.reader;
console.log(data.jqXHR);
console.log("File pre upload triggered");
}', */
],
]);
?>
<?= $form->field($model, 'images_array')->hiddenInput()->label(false) ?>
<?php echo '<br>' ?>
<?= Html::submitButton('<i class="glyphicon glyphicon-save-file"></i> UPLOAD FILE', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary'], ['students/create']) ?>
<?php ActiveForm::end(); ?>
<?php
$script = <<< JS
// initialize array
var uploaded_images = [];
JS;
$this->registerJs($script);
?>
Here Controller file:
<?php
/*
* Post products Images Upload Action Via FileInput Yii2 Extention.
*/
public function actionUpload() {
$files = array();
$allwoedFiles = ['jpg', 'png'];
if ($_POST['is_post'] == 'update') {
$products_id = $_POST['products_id'];
if ($_FILES) {
$tmpname = $_FILES['ProductsMaster']['tmp_name']['products_image'][0];
$fname = $_FILES['ProductsMaster']['name']['products_image'][0];
//Get the temp file path
$tmpFilePath = $tmpname;
//Make sure we have a filepath
if ($tmpFilePath != "") {
//save the filename
$shortname = $fname;
$size = $_FILES['ProductsMaster']['size']['products_image'][0];
$ext = substr(strrchr($shortname, '.'), 1);
if (in_array($ext, $allwoedFiles)) {
//save the url and the file
$newFileName = Yii::$app->security->generateRandomString(40) . "." . $ext;
//Upload the file into the temp dir
if (move_uploaded_file($tmpFilePath, 'uploads/products/' . $newFileName)) {
$productsImages = new productsImages();
$productsImages->products_id = $products_id;
$productsImages->image_for = 'products';
$productsImages->image = 'uploads/products/' . $newFileName;
$productsImages->created_at = time();
$productsImages->save();
$files['initialPreview'] = Url::base(TRUE) . '/uploads/products/' . $newFileName;
$files['initialPreviewAsData'] = true;
$files['initialPreviewConfig'][]['key'] = $productsImages->id;
return json_encode($files);
}
}
}
} /* else {
return json_encode(['error' => 'No files found for pload.']);
} */
return json_encode($files);
} else {
if (isset($_POST)) {
if ($_FILES) {
$files = ProductsMaster::SaveTempAttachments($_FILES);
return json_encode($files);
$result = ['files' => $files];
Yii::$app->response->format = trim(Response::FORMAT_JSON);
return $result;
} /* else {
echo json_encode(['error' => 'No files found for pload.']);
} */
}
}
}
/**
* Uploaded Images Delete Action on Update Forms Action
* #return boolean
*/
public function actionDeleteImage() {
$key = $_POST['key'];
if (is_numeric($key)) {
$products_image = ProductsImages::find()->where(['id' => $key])->one();
unlink(Yii::getAlias('#webroot') . '/' . $products_image->image);
$products_image->delete();
return true;
} else {
unlink(Yii::getAlias('#webroot') . '/uploads/products/temp/' . $key);
return true;
}
}
/**
** Create Products
**/
public function actionCreate() {
//Products Images
// temp store image moved and save to database.. with generated forms..
if (count($model->images_array) > 0) {
$images_array = explode(',', $model->images_array);
if (!empty($images_array) && $model->images_array != '') {
foreach ($images_array as $image) {
$file = Yii::$app->basePath . '/uploads/products/temp/' . $image;
$rename_file = Yii::$app->basePath . '/uploads/products/' . $image;
rename($file, $rename_file);
$productsImages = new productsImages();
$productsImages->products_id = $model->id;
$productsImages->image_for = 'products';
$productsImages->image = 'uploads/products/' . $image;
$productsImages->created_at = time();
$productsImages->save();
}
}
}
}
?>
Here Model
I added a load function to the attachment model.
<?php
/*
* Save Temp Images
*/
public static function SaveTempAttachments($attachments) {
$files = "";
$allwoedFiles = ['jpg', 'png'];
if ($_FILES) {
$tmpname = $_FILES['ProductsMaster']['tmp_name']['products_image'];
$fname = $_FILES['ProductsMaster']['name']['products_image'];
if (!empty($attachments)) {
if (count($fname) > 0) {
//Loop through each file
for ($i = 0; $i < count($fname); $i++) {
//Get the temp file path
$tmpFilePath = $tmpname[$i];
//Make sure we have a filepath
if ($tmpFilePath != "") {
//save the filename
$shortname = $fname[$i];
$size = $attachments['ProductsMaster']['size']['products_image'][$i];
$ext = substr(strrchr($shortname, '.'), 1);
if (in_array($ext, $allwoedFiles)) {
//save the url and the file
$newFileName = Yii::$app->security->generateRandomString(40) . "." . $ext;
//Upload the file into the temp dir
if (move_uploaded_file($tmpFilePath, 'uploads/products/temp/' . $newFileName)) {
$files['initialPreview'] = Url::base(TRUE) . '/uploads/products/temp/' . $newFileName;
$files['initialPreviewAsData'] = true;
// $files['uploadExtraData'][]['is_post'] = 'new';
$files['initialPreviewConfig'][]['key'] = $newFileName;
}
}
}
}
}
}
}
return $files;
}
?>

I am trying to find a "simple" way to store images (and data about them) using CakePHP and MySQL.This code has got me a bit confused

I went through this article to make a file uploading site with Cakephp,
http://www.tuxradar.com/content/cakephp-tutorial-build-file-sharing-application
I suppose the relevant code to this question is this, a download and an upload function,
function add() {
if (!empty($this->data)) {
$this->Upload->create();
if ($this->uploadFile() && $this->Upload->save($this->data)) {
$this->Session->setFlash(__('The upload has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The upload could not be saved. Please, try again.', true));
}
}
$users = $this->Upload->User->find('list');
$users = $this->Upload->User->find('list');
$this->set(compact('users', 'users'));
}
function uploadFile() {
$file = $this->data['Upload']['file'];
if ($file['error'] === UPLOAD_ERR_OK) {
$id = String::uuid();
if (move_uploaded_file($file['tmp_name'], APP.'uploads'.DS.$id)) {
$this->data['Upload']['id'] = $id;
$this->data['Upload']['filename'] = $file['name'];
$this->data['Upload']['filesize'] = $file['size'];
$this->data['Upload']['filemime'] = $file['type'];
return true;
}
}
return false;
}
function download($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid id for upload', true));
$this->redirect(array('action' => 'index'));
}
$this->Upload->bindModel(array('hasOne' => array('UploadsUser')));
$upload = $this->Upload->find('first', array(
'conditions' => array(
'Upload.id' => $id,
'OR' => array(
'UploadsUser.user_id' => $this->Auth->user('id'),
'Upload.user_id' => $this->Auth->user('id'),
),
)
));
if (!$upload) {
$this->Session->setFlash(__('Invalid id for upload', true));
$this->redirect(array('action' => 'index'));
}
$this->view = 'media';
$filename = $upload['Upload']['filename'];
$this->set(array(
'id' => $upload['Upload']['id'],
'name' => substr($filename, 0, strrpos($filename, '.')),
'extension' => substr(strrchr($filename, '.'), 1),
'path' => APP.'uploads'.DS,
'download' => true,
));
}
I am not quite sure what all that code is doing actually, but I am trying to make a page so I can display one of the images instead of downloading them. If make this statement,
<?php echo $this->Html->image('/uploads/download/'.$upload['Upload']['id']);?>
My webpage displays my image but I don't actually have a download folder, I added that extension because it appears that the download function adds it for some reason. If someone could explain what is happening there, that would be great.
You need to make a new controller method to view your images individually, something like this:
public function view($id = null) {
if (!$this->Upload->exists($id)) {
throw new NotFoundException(__('Invalid upload'));
}
$options = array('conditions' => array('Upload.' . $this->Upload->primaryKey => $id));
$this->set('upload', $this->Upload->find('first', $options));
}
And then display the image in your /View/Uploads/view.ctp:
<?php echo $this->Html->image('/uploads/download/'.$upload['Upload']['id']);?>