I know how do upload an object to Aws S3 Bucket like this:
try {
$oClientAws->putObject(array(
'Bucket' => 'bucket_test',
'Key' => 'fileName.jpg',
'Body' => fopen('path/to/file/fileName.jpg', 'r'),
'ACL' => 'public-read',
));
}
catch (Aws\Exception\S3Exception $e) {}
But i don't know how to download an object i can use $oClientAws->getObject(parms...) and change the content type of the header but this just show my file on the browser, but don't download the file.
tks!
File can be downloaded from s3 bucket using getObject method of s3client API
/**
* Gets file stored in Amazon s3 bucket.
*
* #param string $awsAccesskey , access key used to access the Amazon bucket.
* #param string $awsSecretKey , secret access key used to access the Amazon bucket.
* #param string $bucketName , bucket name from which the file is to be accessed.
* #param string $file_to_fetch , name of the file to be fetched, if the file is with in a folder it should also include the folder name.
* #param string $path_to_save , path where the file received should be saved.
* #return boolean true if the file is successfully received and saved else returns false.
*/
function get_from_s3_bucket( $awsAccesskey, $awsSecretKey, $bucketName, $file_to_fetch, $path_to_save ) {
try {
$bucket = $bucketName;
require_once('S3.php');
$s3 = new S3( $awsAccesskey, $awsSecretKey );
$object = $s3->getObject( $bucket, $file_to_fetch, $path_to_save );
if ( $object->code == 200 ) {
return true;
} else {
return false;
}
} catch ( Exception $e ) {
return false;
}
}
Refer the below link for more guidance:
http://docs.aws.amazon.com/aws-sdk-php/latest/class-Aws.S3.S3Client.html
Using the S3 standalone class (which I have found isn't much different from the AWS SDK) getObject has a saveTo param where you pass a filename to save the file to... Check out the method:
/**
* Get an object
*
* #param string $bucket Bucket name
* #param string $uri Object URI
* #param mixed $saveTo Filename or resource to write to
* #return mixed
*/
public static function getObject($bucket, $uri, $saveTo = false)
{
$rest = new S3Request('GET', $bucket, $uri, self::$endpoint);
if ($saveTo !== false)
{
if (is_resource($saveTo))
$rest->fp =& $saveTo;
else
if (($rest->fp = #fopen($saveTo, 'wb')) !== false)
$rest->file = realpath($saveTo);
else
$rest->response->error = array('code' => 0, 'message' => 'Unable to open save file for writing: '.$saveTo);
}
if ($rest->response->error === false) $rest->getResponse();
if ($rest->response->error === false && $rest->response->code !== 200)
$rest->response->error = array('code' => $rest->response->code, 'message' => 'Unexpected HTTP status');
if ($rest->response->error !== false)
{
self::__triggerError(sprintf("S3::getObject({$bucket}, {$uri}): [%s] %s",
$rest->response->error['code'], $rest->response->error['message']), __FILE__, __LINE__);
return false;
}
return $rest->response;
}
Here's a link to obtain the class: https://aws.amazon.com/code/1448
Hope this helps.
Related
I'm trying to delete the folder created in a bucket in Amazon S3 and it gives the error
An unexpected error has occurred. Please try again.
How can I delete the folder?
First you need to understand that there is nothing like folder in Amazon s3 bucket
what you see is object which behaves like folder
one/ // so what you see folder is this but its separate object
one/abc.png
one/tow/
one/tow/a.zip
to delete folder you need to delete every object start with one/ and you can do that by deleteMatchingObjects() function
$s3 = new Aws\S3\S3Client([
'version' => 'latest',
'region' => 'us-west-2',
'credentials.ini' => [
'key' => $credentials['key'],
'secret' => $credentials['secret'],
],
]);
/* this is what you need*/
$s3->deleteMatchingObjects($bucket, $obj);
I have used phpsdk v3
I am using below code in s3.php class. check it out.
/**
* Delete an empty bucket
*
* #param string $bucket Bucket name
* #return boolean
*/
public function deleteBucket($bucket = '') {
$rest = new S3Request('DELETE', $bucket);
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 204)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false) {
trigger_error(sprintf("S3::deleteBucket({$bucket}): [%s] %s",
$rest->error['code'], $rest->error['message']), E_USER_WARNING);
return false;
}
return true;
}
I am creating a txt/html file in google drive as document using the google drive sdk. the code creates successfully the document.
My question is that it is possible that it can also set the file permission as read-only file?
this is my code in creating the document,
$mkFile = $this->_service->files->insert($file, array('data' => $subcontent, 'mimeType' => 'text/html', 'convert' => true));
You can create Permission to Anyone only reader.
Code based from documentation Google Drive API V3:
https://developers.google.com/drive/api/v3/reference/permissions/create
public function permissionAnyone($fileId) {
$permissions = new Google_Service_Drive_Permission(array(
'role' => 'reader',
'type' => 'anyone',
));
try {
$result = $this->service_drive->permissions->create($fileId, $permissions);
} catch (Exception $e) {
$result = $e->getMessage();
}
return $result;
}
you can use permissions.patch to update the permissions for a file after it has been inserted. There is currently a bug in the API that doesn't allow you to set the permissions at the time you insert the file. You have to patch them after the file has been placed on drive.
Code ripped from documentation link above.
/**
* Patch a permission's role.
*
* #param Google_Service_Drive $service Drive API service instance.
* #param String $fileId ID of the file to update permission for.
* #param String $permissionId ID of the permission to patch.
* #param String $newRole The value "owner", "writer" or "reader".
* #return Google_Servie_Drive_Permission The patched permission. NULL is
* returned if an API error occurred.
*/
function patchPermission($service, $fileId, $permissionId, $newRole) {
$patchedPermission = new Google_Service_Drive_Permission();
$patchedPermission->setRole($newRole);
try {
return $service->permissions->patch($fileId, $permissionId, $patchedPermission);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
}
I am trying to upload a pdf to google drive as a service account in php.
I get a browser error: ERR_CONNECTION_RESET when trying to upload.
I got the code from here:
https://developers.google.com/drive/web/service-accounts#next_steps
and
https://developers.google.com/drive/v2/reference/files/insert
<?php
require_once "google-api-php-client/src/Google_Client.php";
require_once "google-api-php-client/src/contrib/Google_DriveService.php";
require_once "google-api-php-client/src/contrib/Google_Oauth2Service.php";
session_start();
$DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
$SERVICE_ACCOUNT_EMAIL = 'xxx#developer.gserviceaccount.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'API Project-xxx.p12';
/**
* Build and returns a Drive service object authorized with the service accounts.
*
* #return Google_DriveService service object.
*/
function buildService() {
global $DRIVE_SCOPE, $SERVICE_ACCOUNT_EMAIL, $SERVICE_ACCOUNT_PKCS12_FILE_PATH;
$key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
$auth = new Google_AssertionCredentials(
$SERVICE_ACCOUNT_EMAIL,
array($DRIVE_SCOPE),
$key);
$client = new Google_Client();
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);
return new Google_DriveService($client);
}
/**
* Insert new file.
*
* #param Google_DriveService $service Drive API service instance.
* #param string $title Title of the file to insert, including the extension.
* #param string $description Description of the file to insert.
* #param string $parentId Parent folder's ID.
* #param string $mimeType MIME type of the file to insert.
* #param string $filename Filename of the file to insert.
* #return Google_DriveFile The file that was inserted. NULL is returned if an API error occurred.
*/
function insertFile($service, $title, $description, $parentId, $mimeType, $filename) {
$file = new Google_DriveFile();
$file->setTitle($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($parentId != null) {
$parent = new Google_ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));
}
try {
$data = file_get_contents($filename);
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
));
// Uncomment the following line to print the File ID
// print 'File ID: %s' % $createdFile->getId();
return $createdFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
$service=buildService();
$title='test';
$description='qqq';
$parentId='';
$mimeType='application/pdf';
$filename='doc.pdf';
insertFile($service, $title, $description, $parentId, $mimeType, $filename)
?>
I'm trying to upload a local CSV-file to Google Drive and display it like a Google Spreadsheet there. However, when I go to my Google Drive and click the link to my file, I can only download it, not view it as a spreadsheet. I've tried using the ?convert=true but the file doesn't get converted. I've also tried using application/vnd.google-apps.spreadsheet as the mime type but noting changes or I get a 400 Bad request response.
When I right click the file, I can choose to open with Google Spreadsheets which then displays the file correctly. I can't find anything about this in the current documentation over at Google and searches on google haven't help a whole lot.
What I've done so far is creating a new, empty Google spreadsheet and tried filling it with my CSV file but that gives me a 500 Internal Error.
$file = new Google_DriveFile();
$file->setTitle('Exported data from ' . $this->event->title);
$file->setDescription('Exported data from ' . $this->event->title);
$file->setMimeType( 'text/csv' );
try {
$createdFile = $this->drive->files->insert($file, array(
'data' => $data,
'mimeType' => 'application/vnd.google-apps.spreadsheet'
), array('convert'=>true));
// Uncomment the following line to print the File ID
// print 'File ID: %s' % $createdFile->getId();
$additionalParams = array(
'newRevision' => false,
'data' => $data,
'convert'=>true //no change if this is true or false
);
$newFile = $this->drive->files->get( $createdFile->getId() );
$newFile->setMimeType('text/csv');
$updated = $this->drive->files->update($createdFile->getId(), $newFile, $additionalParams);
preint_r($updated);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
I've looked at the API for Google Drive but haven't found anything useful. I'm wondering if I should use the Google Spreadsheets API or is the Google Drive API the one to use solely?
Many thanks in advance,
Waldemar
Try the following. It's from the File:insert reference in the Google documentation but I added the convert parameter:
/**
* Insert new file.
*
* #param Google_DriveService $service Drive API service instance.
* #param string $title Title of the file to insert, including the extension.
* #param string $description Description of the file to insert.
* #param string $parentId Parent folder's ID.
* #param string $mimeType MIME type of the file to insert.
* #param string $filename Filename of the file to insert.
* #return Google_DriveFile The file that was inserted. NULL is returned if an API error occurred.
*/
function insertFile($service, $title, $description, $parentId, $mimeType, $filename) {
$file = new Google_DriveFile();
$file->setTitle($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($parentId != null) {
$parent = new ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));
}
try {
$data = file_get_contents($filename);
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
'convert' => true,
));
// Uncomment the following line to print the File ID
// print 'File ID: %s' % $createdFile->getId();
return $createdFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
i am try above code it will not working for me
it will just stop after login
just use
$file->setMimeType('application/vnd.google-apps.spreadsheet);
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'text/csv',
'convert' => true,
));
it will work for me
I have to add another parameters to make it work.
'uploadType' => 'multipart'
$createdFile = $service->files->insert($file,array(
'data' => $data,
'mimeType' => 'text/csv',
'convert' => true,
'uploadType' => 'multipart',
));
Now it's working.
I need to create spreadsheet using google drive PHP API, how can i do that ?
i already have code put it always get untitled file and when i click on it there is no data here is my code:
/**
* Insert new file.
*
* #param apiDriveService $service Drive API service instance.
* #param string $title Title of the file to insert, including the extension.
* #param string $description Description of the file to insert.
* #param string $parentId Parent folder's ID.
* #param string $mimeType MIME type of the file to insert.
* #param string $filename Filename of the file to insert.
* #return DriveFile The file that was inserted. NULL is returned if an API error occurred.
*/
function insertFile($service, $title, $description, $parentId, $mimeType, $data) {
$file = new DriveFile();
$file->setTitle($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($parentId != null) {
$parentsCollectionData = new DriveFileParentsCollection();
$parentsCollectionData->setId($parentId);
$file->setParentsCollection(array($parentsCollectionData));
}
try {
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
));
// Uncomment the following line to print the File ID
// print 'File ID: %s' % $createdFile->getId();
print_r($createdFile);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
if(isset($_POST['insertFile'])){
$service = new apiDriveService($client);
insertFile($service,'Google Maps Mrakers.txt','ADD Google Map Mrakers To File',NULL,'text/plain',$_POST['data']);
exit;
}
You are having this issue because you are using an out-of-date version of the PHP client library. Please sync your client to the trunk of the project repository.
You would have to re-write some of your code as the client library has been refactored since you first wrote your code. The reference guides in the Google Drive SDK documentation have been updated to reflect this refactoring.
To create a Google Spreadsheet, insert a file without content with its mimeType set to application/vnd.google-apps.spreadsheet.