I am using sample code from googles site and this throws no exceptions but returns no results.
If I use the API explorer the same data works just fine. I have tried different files (all from google sample code) different settings. All of which give me the same result, Nothing.
function transcribe_sync($content)
{
// set string as audio content
$audio = (new RecognitionAudio())
->setContent($content);
// set config
$encoding = AudioEncoding::LINEAR16;
$sampleRateHertz = 32000;
$languageCode = 'en-US';
$config = (new RecognitionConfig())
->setEncoding($encoding)
->setSampleRateHertz($sampleRateHertz)
->setAudioChannelCount(1)
->setMaxAlternatives(1)
->setLanguageCode($languageCode);
// create the speech client
$client = new SpeechClient();
try {
$response = $client->recognize($config, $audio);
echo $response->getResults()
}
catch (\Exception $e) {
$this->handleError('Error determining recognition. ' . $e->getMessage());
}
finally {
$client->close();
}
My resolution to this issues was the way I was passing the file (don't think the file was being populated correctly or at all). It was weird that I did not get an error. Because of the length of my audio files, I ended up integrating google storage to upload the file () and used:
$audio = (new RecognitionAudio())->setUri("gs://...");
... longRunningRecognize($config, $audio);
Hope this helps someone.
Using Laravel/Snappy to generate PDFs. However this errors:
already exist file name after trying to save it to storage.
How can I handle these errors?
public function saveSnappyHeaderFooter()
{
//dd( storage_path());
$users = \App\User::all();
$data = ['users' => $users];
$SnappyPDF = SnappyPDF::loadView('pdf.snappyPDF.snappyHeaderFooter', $data);
$SnappyPDF->setOption('margin-top', '25mm');
$SnappyPDF->setOption('margin-bottom', '25mm');
$SnappyPDF->setOption('header-html', public_path() . '\pdf-parts\pdf-header.html');
$SnappyPDF->setOption('footer-html', public_path() . '\pdf-parts\pdf-footer.html');
$SnappyPDF->setOption('print-media-type', true);
$SnappyPDF->save(storage_path('app/files/'.Carbon::now() .'_' . 'myname2.pdf'));
}
In general this is how you can handle errors in PHP:
try {
//your code
} catch (Exception $e) {
//handle errors
}
Or you can ask if file exists by using:
if(!file_exists(storage_path('app/files/'.Carbon::now() .'_' . 'myname2.pdf'))){
//ok, code will run
}else{
// not ok, maybe change the name?
}
you can also do it in the laravel way: File::exists
Or maybe you can give us more details.
Note
Its an anti-patteren to not be 100% sure that the files is not exists. I dont know your usecase, but im saying that based on the fact that you are generating the file name. maybe you should use more uniq patterens. like GUIDs...
public function uploadNotaCorte(Request $request, EstadoRepository $estadoRepository)
{
$error = array();
$path = $request->file('file')->getRealPath();
$notasCorte = Excel::load($path, function($reader) {
})->get();
$chunk = $notasCorte->chunk(100);
foreach ($notasCorte as $key => $notaCorte) {
//RULES
}return $error;
}
**
Hi everyone, I'm new to programming and I'm having a hard time implementing the chunk method, so the dodigo above usually works on small files plus larger error files because of the size.
I need to upload a file with 120,000 records and I am trying to use the chunk for this, I do not know what I can do wrong already looked at the documentation more and very simple and I could not solve the problem can anyone help me ??**
Assuming you're using the maatwebsite/excel package, this link should help: http://www.maatwebsite.nl/laravel-excel/docs/import#chunk
You'll want to change your code to something like this:
public function uploadNotaCorte(Request $request, EstadoRepository $estadoRepository)
{
$error = array();
$path = $request->file('file')->getRealPath();
Excel::filter('chunk')->load($path)->chunk(100, function($results)
{
foreach($results as $row)
{
// RULES
}
});
return $error;
}
This isn't tested and I've never used that package (though good to know it exists) so your mileage may vary.
Before explaining the problem. Let me show the controller function:
public function storePost(IdeaRequest $request)
{
$idea = new Idea();
$idea->idea_title = $request->input('idea_title');
$idea->user_id = $request->input('user_id');
$idea->idea_image = $request->file('idea_image')->move('publicPages\images')->getClientOriginalName();
$idea->idea_info = $request->input('idea_info');
$idea->selection = $request->input('selection');
$idea->idea_location = $request->input('idea_location');
$idea->idea_goal = $request->input('idea_goal');
$idea->idea_description = $request->input('idea_description');
$idea->save();
session()->flash('flash_message', 'Your idea has been submitted for Review');
return back();
}
It stores the image as .tmp file. Things I have tried out
guessExtension(), It just returns the extension name and does not
even store the image.
getClientOriginalName(), it throws an error;
getClientOriginalName method is not defined. I have searched the
method and it is in there. used its namespace
Symfony\Component\HttpFoundation\File\UploadedFile. it did not work
either.
Tried different things out from stackoverflow, Nothing has worked
for me till now. In other words, i have invested a lot of time to
solve this problem but nothing worked. Any help would highly be
appreciated.
Here you go:
public function storePost(IdeaRequest $request)
{
$request->file('idea_image')->move('publicPages\images');
$filename = $request->file('idea_image')->getClientOriginalName();
$idea = new Idea();
$idea->idea_title = $request->input('idea_title');
$idea->user_id = $request->input('user_id');
$idea->idea_image = $filename;
$idea->idea_info = $request->input('idea_info');
$idea->selection = $request->input('selection');
$idea->idea_location = $request->input('idea_location');
$idea->idea_goal = $request->input('idea_goal');
$idea->idea_description = $request->input('idea_description');
$idea->save();
session()->flash('flash_message', 'Your idea has been submitted for Review');
return back();
}
Observe closely. You will have to do this in 2 separate lines:
$request->file('idea_image')->move('publicPages\images');
$filename = $request->file('idea_image')->getClientOriginalName();
Why?
move() returns a File object representing the new file.
The File class doesn't have a getClientOriginalName() method. That method belongs to UploadedFile.
When you chain them, you are trying to access getClientOriginalName() from File, which doesn't exist. Have a look at the docs here.
However...
File extends the PHP native SplFileInfo class which has a getFilename() method. So I guess you could also do:
$request->file('idea_image')->move('publicPages\images')->getFilename();
I have uploaded a lot of images from the website, and need to organize files in a better way.
Therefore, I decide to create a folder by months.
$month = date('Yd')
file_put_contents("upload/promotions/".$month."/".$image, $contents_data);
after I tried this one, I get error result.
Message: file_put_contents(upload/promotions/201211/ang232.png): failed to open stream: No such file or directory
If I tried to put only file in exist folder, it worked. However, it failed to create a new folder.
Is there a way to solve this problem?
file_put_contents() does not create the directory structure. Only the file.
You will need to add logic to your script to test if the month directory exists. If not, use mkdir() first.
if (!is_dir('upload/promotions/' . $month)) {
// dir doesn't exist, make it
mkdir('upload/promotions/' . $month);
}
file_put_contents('upload/promotions/' . $month . '/' . $image, $contents_data);
Update: mkdir() accepts a third parameter of $recursive which will create any missing directory structure. Might be useful if you need to create multiple directories.
Example with recursive and directory permissions set to 777:
mkdir('upload/promotions/' . $month, 0777, true);
modification of above answer to make it a bit more generic, (automatically detects and creates folder from arbitrary filename on system slashes)
ps previous answer is awesome
/**
* create file with content, and create folder structure if doesn't exist
* #param String $filepath
* #param String $message
*/
function forceFilePutContents ($filepath, $message){
try {
$isInFolder = preg_match("/^(.*)\/([^\/]+)$/", $filepath, $filepathMatches);
if($isInFolder) {
$folderName = $filepathMatches[1];
$fileName = $filepathMatches[2];
if (!is_dir($folderName)) {
mkdir($folderName, 0777, true);
}
}
file_put_contents($filepath, $message);
} catch (Exception $e) {
echo "ERR: error writing '$message' to '$filepath', ". $e->getMessage();
}
}
i have Been Working on the laravel Project With the Crud Generator and this Method is not Working
#aqm so i have created my own function
PHP Way
function forceFilePutContents (string $fullPathWithFileName, string $fileContents)
{
$exploded = explode(DIRECTORY_SEPARATOR,$fullPathWithFileName);
array_pop($exploded);
$directoryPathOnly = implode(DIRECTORY_SEPARATOR,$exploded);
if (!file_exists($directoryPathOnly))
{
mkdir($directoryPathOnly,0775,true);
}
file_put_contents($fullPathWithFileName, $fileContents);
}
LARAVEL WAY
Don't forget to add at top of the file
use Illuminate\Support\Facades\File;
function forceFilePutContents (string $fullPathWithFileName, string $fileContents)
{
$exploded = explode(DIRECTORY_SEPARATOR,$fullPathWithFileName);
array_pop($exploded);
$directoryPathOnly = implode(DIRECTORY_SEPARATOR,$exploded);
if (!File::exists($directoryPathOnly))
{
File::makeDirectory($directoryPathOnly,0775,true,false);
}
File::put($fullPathWithFileName,$fileContents);
}
I created an simpler answer from #Manojkiran.A and #Savageman. This function can be used as drop-in replacement for file_put_contents. It doesn't support context parameter but I think should be enough for most cases. I hope this helps some people. Happy coding! :)
function force_file_put_contents (string $pathWithFileName, mixed $data, int $flags = 0) {
$dirPathOnly = dirname($pathWithFileName);
if (!file_exists($dirPathOnly)) {
mkdir($dirPathOnly, 0775, true); // folder permission 0775
}
file_put_contents($pathWithFileName, $data, $flags);
}
Easy Laravel solution:
use Illuminate\Support\Facades\File;
// If the directory does not exist, it will be create
// Works recursively, with unlimited number of subdirectories
File::ensureDirectoryExists('my/super/directory');
// Write file content
File::put('my/super/directory/my-file.txt', 'this is file content');
I wrote a function you might like. It is called forceDir(). It basicaly checks whether the dir you want exists. If so, it does nothing. If not, it will create the directory. A reason to use this function, instead of just mkdir, is that this function can create nexted folders as well.. For example ('upload/promotions/januari/firstHalfOfTheMonth'). Just add the path to the desired dir_path.
function forceDir($dir){
if(!is_dir($dir)){
$dir_p = explode('/',$dir);
for($a = 1 ; $a <= count($dir_p) ; $a++){
#mkdir(implode('/',array_slice($dir_p,0,$a)));
}
}
}