Zend Framework 2: upload and rename multiple files - php

I have a Zend Form and offer the option to upload multiple files with the form. I use dropzone.js. When I upload a single file, everything works fine, I get the Post data and the file gets renamed and moved into the correct folder, but as soon I upload 2 files, I get an Error Message: Notice: Array to string conversion which points to $upload->addFilters('File\Rename'.....
What am I doing wrong here? I have everything in a foreach loop, should this not solve the issue? I can not find a solution for it. Anyone got a tip for me?
Here my Sourcecode so far:
$upload = new \Zend\File\Transfer\Adapter\Http();
// Limit the amount of files
$upload->addValidator('Count', false, 2);
// Limit the MIME type of all given files to gif and jpeg images
$upload->addValidator('MimeType', false, array('image/gif', 'image/jpeg',));
if (!$upload->isValid()) {
$data = new JsonModel(array(
'success' => "failed",
'message' => "validation failed",
));
return $data;
}else{
$files = $upload->getFileInfo();
$upload->setDestination('./public/uploads/tmp/');
// loop through the file array
foreach ($files as $file => $info) {
$file_ext = #strtolower(#strrchr($originalName,"."));
$file_ext = #substr($file_ext, 1); // remove dot
$newFilename = md5(uniqid(rand(), true)) .time(). '.' . $file_ext;
$upload->addFilter('File\Rename',
array('target' => $upload->getDestination() . DIRECTORY_SEPARATOR . $newFilename,
'overwrite' => true));
if (!$upload->receive()) {
$data = new JsonModel(array(
'success' => "upload failed",
));
}else{
$data = new JsonModel(array(
'success' => "upload ok",
));
}
return $data;
} // end foreach
}

Related

Upload Excel file Google Drive API

I am using Google Drive API to upload Excel files. I did the API connection correctly. Create a folder and upload the excel file correctly. I can see both of them in my google drive. But, the excel file is empty.. What am I missing here?
my code is below:
$path = "uploads/school_info.xlsx"; //file that I am uploading, inside a folder of my website.
$folder_id = create_folder("School_".$_POST['submit_uid'], "****folder-id****");
$file_name = "School 1";
$success = insert_file_to_drive( $path, $file_name, $folder_id);
// This will insert file into drive and returns boolean values.
function insert_file_to_drive( $file_path, $file_name, $parent_file_id = null ) {
$service = new Google_Service_Drive( $GLOBALS['client'] );
$file = new Google_Service_Drive_DriveFile();
$file->setName( $file_name );
if( !empty( $parent_file_id ) ){
$file->setParents( [ $parent_file_id ] );
}
$result = $service->files->create(
$file,
array(
'data' => file_get_contents($file_path),
//'mimeType' => 'application/octet-stream',
'mimeType' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', //works but still empty excel
)
);
$is_success = false;
if( isset( $result['name'] ) && !empty( $result['name'] ) ){
$is_success = true;
}
return $is_success;
}
ok I found what was the problem. As I wrote in my code above, I had a relative path
$path = "uploads/school_info.xlsx";
when I changed it to full path like this:
$path = "https://www.example.com/uploads/school_info.xlsx";
everything works as expected
thank you all for your time
Answer
I have successfully uploaded a .xlsx file with the following code. Apparently it is very similar to yours, I just change the mimeType and add the uploadType. Once the file is uploaded, from the UI version of Drive, I can access and view the contents of the file. In case it still fails, please repeat the process by downloading a sample file from here.
Code
$service = new Google_Service_Drive($client);
$file = new Google_Service_Drive_DriveFile();
$file->setName('test.xlsx');
$data = file_get_contents('file_example_XLSX_50.xlsx');
$result = $service->files->create($file, array(
'data' => $data,
'mimeType' => 'application/vnd.ms-excel',
'uploadType' => 'multipart'
));

Using the Google Drive API for PHP, What is the proper way to upload a file while setting the "keepRevisionForever" to true?

I am trying to allow file uploads to overwrite the previous copy and keep the revision history permanent within Google Drive. Also...Do I need to upload with a set ID or is the file name going to overwrite natively?
Here is a sample of what I have as a test function:
function uploadFile($filename = "")
{
$title="testFile";
$description="Testing the upload of the file";
$mimeType="image/jpeg";
$filename = ROOTPATH."IMG_1232.JPG"; //Temporarily overriding $filename for testing.
$file = new Google_Service_Drive_DriveFile();
$file->setName($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($parentId != null) {
$parent = new Google_Service_Drive_ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));
}
try {
$data = file_get_contents($filename);
$this->startGDService();
$createdFile = $this->service->files->create($file, array(
'data' => $data,
'mimeType' => $mimeType,
'keepRevisionForever' => true // <---This doesn't seem to work.
));
return $createdFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return;
}
Looks like I was using the wrong function. The create function will always create a file on the drive. To overwrite a particular file, you need to use the update() function. See here:
function updateFile($filename, $fileID)
{
$this->startGDService();
$filename = UPLOAD_PATH.$filename;
$mimetype = mime_content_type ($filename);
try {
$emptyFile = new Google_Service_Drive_DriveFile();
$data = file_get_contents($filename);
$this->service->files->update($fileID, $emptyFile, array(
'data' => $data,
'mimeType' => $mimetype,
'uploadType' => 'multipart',
'keepRevisionForever' => true
));
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}

Google API PHP Update File

I'm trying to update the content of the file. Use the PHP function:
function updateFile($service, $fileId, $newTitle, $newDescription, $newMimeType, $newFileName, $newRevision) {
try {
// First retrieve the file from the API.
$file = $service->files->get($fileId);
// File's new metadata.
$file->setTitle($newTitle);
$file->setDescription($newDescription);
$file->setMimeType($newMimeType);
// File's new content.
$data = file_get_contents($newFileName);
$additionalParams = array(
'newRevision' => $newRevision,
'data' => $data,
'mimeType' => $newMimeType
);
// Send the request to the API.
$updatedFile = $service->files->update($fileId, $file, $additionalParams);
return $updatedFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
....
$data = retrieveAllFiles($service);
$fileName = 'test.txt';
$mimeType = mime_content_type('./'.$fileName);
$res = updateFile($service, $data[0]['id'], $data[0]['title'], 'update', $mimeType, $fileName, true);
I'm trying to add a text file line "test string". Function updates the data file (description, lastModifyingUser...), but the content of the file remains the same. Who can tell what's wrong?
In additionalParams need to add :
'uploadType' => 'multipart',
or
'uploadType' => 'media',
Hope it helps!

Google Drive PHP API empty uploaded file

So I've been having weird issues with PHP upload with GAPI. The file actually gets created on the drive but for some reason the data doesn't make it to Google and it just creates a file with 0 bytes.
Here's my code:
function uploadFile($service, $title, $description, $parentId, $mimeType, $filepath) {
$mimeType = "image/png";
$title = "test.png";
$file = new Google_Service_Drive_DriveFile();
$file->setTitle($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($parentId != null) {
$parent = new Google_Service_Drive_ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));
}
try {
$data = file_get_contents();
$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) {
echo "An error occurred: " . $e->getMessage();
}
}
Everything is authenticated so I know that's not the problem. When I output $data, I get the mess of crap that you usually get when pulling a file so I know that's not the issue.. All of the scopes should be right but here they are anyways:
$client->addScope("https://www.googleapis.com/auth/drive");
$client->addScope("https://www.googleapis.com/auth/drive.file");
$client->addScope("https://www.googleapis.com/auth/drive.appdata");
$client->addScope("https://www.googleapis.com/auth/drive.scripts");
$client->addScope("https://www.googleapis.com/auth/drive.apps.readonly");
$client->addScope("https://www.googleapis.com/auth/drive.metadata.readonly");
$client->addScope("https://www.googleapis.com/auth/drive.readonly");
No documentation I can find on this problem so any help would be really appreciated!
I was able to figure this out and wanted to leave this for anyone else that might have this issue.
Ended up looking through the source code and noticed an If statement that was not getting fired.
Change
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
));
To
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
'uploadType' => 'media' //add this for pdfs to work
));
It's just that easy! Hate it when it's that easy..

Uploading facebook event picture throws error

I am trying to create event with picture, but when i upload picture to facebook it throws me an error (#324) Missing or invalid image file
this is the function to upload picture.
public function uploadFacebookEventPicture($fullPath, $eventId) {
$mainImage = '#' . $fullPath;
$imgData = array(
'picture' => $mainImage
);
try {
$data = $this->facebook->api('/'.$eventId, 'post', $imgData);
return $data;
} catch (FacebookApiException $e) {
error_log('Failed to attach picture to event. Exception: ' . $e->getMessage());
}
return null;
}
the par of code i use after form post
if ($file[$name]['error'] == 0) {
$fileName = $file[$name]['name'];
$fileInfo = pathinfo($fileName);
$newFileName = md5($fileName . microtime()) . '.' . $fileInfo['extension'];
$fullPath = $this->config->applications->uploadPath . $newFileName;
$form->$name->addFilter('Rename', $fullPath);
if ($form->$name->receive()) {
$resize = new SimpleImage();
$resize->load($fullPath);
$resize->resizeToWidth($this->config->applications->resize->width);
$resize->save($fullPath);
// Gathering data for saving files information
$fileInfo = array(
'name' => $newFileName,
'type' => FileTypes::IMAGE,
'description' => 'Application: Uploaded from Events form in back-end',
);
$fileId = $dbFiles->save($fileInfo);
$eventFileData = array(
'event_id' => $eventId,
'file_id' => $fileId,
'main_image' => ($name == 'mainImage') ? 1 : 0
);
$dbEventFiles->save($eventFileData);
if ($name === 'mainImage') {
$success = **$this->uploadFacebookEventPicture($fullPath, $eventData['fb_event_id']**);
}
}
}
facebook object is created with upload file true
$facebook = new Facebook(array(
'appId' => $config->facebook->appId,
'secret' => $config->facebook->secret,
'fileUpload' => true
));
According to Facebook bug tracker, this bug has been fixed:
Bug tracker post
Status changed to Fixed
Code above works fine for uploading facebook event picture.

Categories