trying to download a csv file, during downloading the page is opened in new tab and showing the error as FileNotFoundException in File.php line 37: The file "72" does not exist. Ccan anyone please help me?
Laravel controller:
public function fileExport(Request $request, Response $response)
{
$employee = Employee::all()->toArray();
$fileName = 'Employee.csv';
$headers = array(header('Content-Type: application/csv', 'Content-Disposition: attachment; filename="'.$fileName.'"'));
$f = fopen('php://output', 'w');
foreach ($employee as $line)
{
$data = fputcsv($f, $line);
}
return response()->download($data,$headers);
}
Laravel router:
Route::get('fileExport', 'EmployeeController#fileExport');
Angularjs controller:
$scope.exportFile = function(){
$window.open(rootUrl+'fileExport');
}
<button class="btn btn-default btn-xs btn-detail" ng-click="exportFile()">Export</button>
Exception shows that file is not found and might not be generated.
First of all check file exists and paths are correct?
And if file does not exists then make it simple as below and create the file correctly on desired path and then you can move on:
$f = fopen($fileName, 'w');
Related
How do I save a remote file to local storage in Typo3 v10.
Having the following code, no files are getting saved in fileadmin storage
private function saveFileFromUri($fileUrl)
{
$urlParts = parse_url($fileUrl);
$pathParts = pathinfo($urlParts['path']);
$fileName = $pathParts['basename'];
$file = GeneralUtility::getUrl($fileUrl);
$temporaryFile = GeneralUtility::tempnam('temp/' . $fileName);
$storage = $this->defaultStorage->createFolder($pathParts['dirname']);
if ($file === false) {
$error = sprintf(
'File %s could not be fetched.',
$fileUrl
);
if (isset($report['message'])) {
$error .= ' ' . sprintf(
'Reason: %s (code: %s)',
$report['message'],
$report['error'] ?? 0
);
}
throw new \TYPO3\CMS\Core\Resource\Exception\ResourceDoesNotExistException(
$error,
1613555057
);
}
\TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($file);
GeneralUtility::writeFileToTypo3tempDir(
$temporaryFile,
$file
);
$fileObject = $storage->addFile(
$temporaryFile,
$storage,
$fileName
);
\TYPO3\CMS\Extbase\Utility\DebuggerUtility::var_dump($fileObject);
}
What is the right way to save remote files in typo3 and create a fileObject?
TYPO3 has an API to get or add files via the File Abstraction Layer (FAL).
This example adds a new file in the root folder of the default storage:
$storageRepository = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\StorageRepository::class);
$storage = $storageRepository->getDefaultStorage();
$newFile = $storage->addFile(
'/tmp/temporary_file_name.ext',
$storage->getRootLevelFolder(),
'final_file_name.ext'
);
Please refer to the documentation for details.
I'm not able to figure out what's wrong in my code.
In my project the user is allowed to upload multiple pictures for each aircraft registration number; I want to rename each uploaded files with the following rules: registration id, minus sign, progressive number; so if the user upload a new image file for the registration id xxx, the uploaded filename becomes xxx-1.jpg
The code to upload the multiple files is the following; it works fine so far...
// Count uploaded files
$countfiles = count($_FILES['files']['name']);
// Define new image name
$image = $id . '-1.jpg';
for($i=0;$i<$countfiles;$i++)
{
if(!empty($_FILES['files']['name'][$i]))
{
// Define new $_FILES array - $_FILES['file']
$_FILES['file']['name'] = $_FILES['files']['name'][$i];
$_FILES['file']['type'] = $_FILES['files']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['files']['tmp_name'][$i];
$_FILES['file']['error'] = $_FILES['files']['error'][$i];
$_FILES['file']['size'] = $_FILES['files']['size'][$i];
// Check if the image file exist and modify name in case
$filename = $this->_file_newname($uploaddir,$image);
// Set preference
$config['upload_path'] = $upload_path;
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['max_size'] = '5000';
$config['file_name'] = $filename;
//Load upload library
$this->load->library('upload',$config);
$arr = array('msg' => 'something went wrong', 'success' => false);
// File upload
if($this->upload->do_upload('file'))
{
$data = $this->upload->data();
}
}
}
The _file_newname() function does the file renaming jog, here you are the code:
private function _file_newname($path, $filename)
{
if ($pos = strrpos($filename, '.')) {
$name = substr($filename, 0, $pos);
$ext = substr($filename, $pos);
} else {
$name = $filename;
}
$newpath = $path.$filename;
$newname = $filename;
if(file_exists($newpath)){
$counter = 1;
if($pos = strrpos($name, '-')) {
$oldcounter = substr($name, $pos + 1);
if(is_numeric($oldcounter)){
$counter = $oldcounter++;
$name = substr($name, 0, $pos);
}
}
$newname = $name . '-' . $counter . $ext;
$newpath = $path . $newname;
while (file_exists($newpath)) {
$newname = $name .'-'. $counter . $ext;
$newpath = $path.$newname;
$counter++;
}
}
return $newname;
}
Now...the issue....the renaming function works fine if the user upload one file each time...so the first upload set the file name xxx-1.jpg, the second upload set the filename to xxx-2.jpg and so on....but....if the user upload more then one file at time...the second file become xxx-1x.jpg.
If already exists one file on server ( for example xxx-1.jpg ) and the user upload two more files..they are renamed as xxx-2.jpg ( correct) and xxx-21.jpg (wrong...should be xxx-3.jpg).
Any hint or suggestion to fix the issue?
Thanks a lot
Your new file name is out of the loop for the uploaded photos.
So it becomes static.
Put that line inside the loop:
// Define new image name
$image = $id . '-' . $i . '.jpg';
This way you are gonna keep the $id and rename the files according to the iteration of the loop - $i.
The following is my php script for you to upload video files (max 100MB) to my server.
Problem is, it uploads one mp4 file without any problems. But when I try uploading others it gives these errors.
When I try uploading "T.J. Hooker (1982) - Season 1 OPENING.mp4" which is 2.57MB, I get this error:
array(1) { ["id_verification_video_file"]=> array(5) { ["name"]=>
string(41) "T.J. Hooker (1982) - Season 1 OPENING.mp4" ["type"]=>
string(0) "" ["tmp_name"]=> string(0) "" ["error"]=> int(1) ["size"]=>
int(0) } } Array ( [id_verification_video_file] => Array ( [name] => T.J.
Hooker (1982) - Season 1 OPENING.mp4 [type] => [tmp_name] => [error] => 1
[size] => 0 ) )
Q1. What does this error mean ?
When I try uploading another file "Taekwondo vs Jeet Kune Do.mp4" which is 9.32MB, I get the following error:
"array(0) { } Upload your video file".
Q2. Why am I getting line 17 triggered when I am trying to upload a video (mp4) file ?
Line 17:
if(!isset($_FILES["id_verification_video_file"]))
{
echo "Upload your video file";
exit;
}
Full Script:
<?php
$conn = mysqli_connect("localhost","livefoll_user","livefollow_2019*","livefoll_live
follow");
if (!$conn)
{
$error = mysqli_connect_error();
$errno = mysqli_connect_errno();
print "$errno: $error\n";
exit();
}
if($_SERVER["REQUEST_METHOD"] == "POST")
{
var_dump($_FILES);
//Check whether the file was uploaded or not without any errors.
if(!isset($_FILES["id_verification_video_file"]))
{
echo "Upload your video file";
exit;
}
elseif (!$_FILES["id_verification_video_file"]["error"] == 0)
{
$Errors = Array();
$Errors[] = "Error: " . $_FILES["id_verification_video_file"] ["ERROR"]; print_r($_FILES); ?><br><?php
print_r($_ERRORS);
exit();
}
else
{
$user = 'livefoll_user';
//Feed Id Verification Video File Upload Directory path.
$directory_path = 'uploads/videos/id_verifications/';
//Make Directory under $user in 'uploads/videos/id_verifications' Folder.
$directory_path_and_user_dir = "uploads/videos/id_verifications/$user";
if(!is_dir($directory_path_and_user_dir))
{
$user = 'livefoll_user';
$mode = 0755;
mkdir($directory_path_and_user_dir,$mode, TRUE);
}
//Grab Uploading File details.
$Errors = Array(); //
$file_name = $_FILES["id_verification_video_file"]["name"];
$file_tmp = $_FILES["id_verification_video_file"]["tmp_name"];
$file_type = $_FILES["id_verification_video_file"]["type"];
$file_size = $_FILES["id_verification_video_file"]["size"];
$file_error = $_FILES['id_verification_video_file']['error'];
//Grab Uploading File Extension details.
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
$directory_path_and_user_dir_and_user_file = "$directory_path_and_user_dir/$file_name";
if(file_exists($directory_path_and_user_dir_and_user_file)) //THIS LINE IS NOT GIVING THE ERROR THAT FILE ALREADY EXISTS. INSTEAD SHOWING A BLANK WHITE PAGE. -> I changed it with 'echo'. It was not giving error because you were just storing the error into the Errors array without throwing the error.
{
echo "Error: You have already uploaded a video file to verify your ID! No need to upload and do it again!";
exit();
}
else
{
//Feed allowed File Extensions List.
$allowed_file_extensions = array("mp4" => "video/mp4");
//Feed allowed File Size.
$max_file_size_allowed_in_bytes = 1024*1024*100; //Allowed limit: 100MB.
$max_file_size_allowed_in_kilobytes = 1024*100; //Allowed limit: 100MB.
$max_file_size_allowed_in_megabytes = 100; //Allowed limit: 100MB.
$max_file_size_allowed = "$max_file_size_allowed_in_bytes";
//Verify File Extension.
if(!array_key_exists($file_extension, $allowed_file_extensions))
{
echo "Error: Select a valid video file format. Select an Mp4, Wav, etc. files.";
exit();
}
//Verify MIME Type of the File.
elseif(!in_array($file_type, $allowed_file_extensions))
{
$Errors[] = "Error: There was a problem uploading your file $file_name! Make sure your file is a video file. You may try again."; //IS THIS LINE CORRECT ? -> yes but won't print if you don't use throwerror or echo ... echo "error: there was a problem... etc..."
exit();
}
//Verify File Size. Allowed Max Limit: 100MB.
elseif($file_size>$max_file_size_allowed)
{
$Errors[] = "Error: Your Video File Size is larger than the allowed limit of: $max_file_size_allowed_in_megabytes.";
exit();
}
$move_to = $directory_path_and_user_dir."/".$file_name;
//Move uploaded File to newly created directory on the server.
if(!move_uploaded_file($file_tmp, $move_to))
{
//user = 'livefoll_user'; //Not necessary
$mode = 0755; //Not necessary
//Notify user their Id Verification Video File uploading failed.
echo "Your Video File \"$file_name\" has failed to be uploaded! You may try some other time.";
exit();
}
else
{
//Notify user their Id Verification Video File was uploaded successfully.
die("Your Video File \"$file_name\" has been uploaded successfully!");
}
}
}
}
?>
<?php //SWITCH FOLLOWING UPLOADING WEB FORM TO HTML5 DESIGN WITH CAPTCHA
AND HIDDEN FIELD/S. FOIL BOTS FROM UPLOADING FILES. MUST BE SQL INJECTION
AND HACKING PROOF.?>
<form METHOD="POST" ACTION="" enctype="multipart/form-data">
<fieldset>
<p align="left"><h3><?php $site_name ?> ID Video Verification
Form</h3></p>
<div class="form-group">
<p align="left"<label>Video File: </label>
<input type="file" name="id_verification_video_file"
id="id_verification_video_file" value="uploaded 'Id Verification Video
File.'"></p>
</div>
</fieldset>
<p align="left"><button type="submit" class="btn btn-default"
name="id_verification_video_file_submit">Submit!</button></p>
</form>
</body>
</html>
Q4. How to solve these issues ? I mean, if the script code is not buggy and manages to upload one mp4 file then it should be able to upload other mp4 files too without showing errors.
Problem solved. The .ini file was restricting the file size.
i have another problem with CakePhp concerning the File & Folder utility.
I am getting this error:
Fatal Error Error: Call to undefined method
RegistriesController::clearStatCache() File:
/var/www/crm0.convieneonline.it/lib/Cake/Utility/File.php Line: 408
what i did it's simple:
I inserted App::uses('Folder', 'Utility'); and App::uses('File', 'Utility'); in the Controller
And then i developed the following code:
$src = 'http://www.website.it/be/preventivatore/img/brands/'. $registry['Registry']['id'] .'.png';
if ($check = File::exists($src)) {
$check = true;
} else {
$check = false;
}
Can you please help me with the error? Thank you
Hi have a strange problem with File::write() in cakephp.
I write this code to generate a pdf view and save it on a file.
private function generate( $id ){
$order = $this->Order->read( null, $id );
$this->set('order', $order);
$view = new View($this);
$viewdata = $view->render('pdf');
//set the file name to save the View's output
$path = WWW_ROOT . 'ordini/' . $id . '.pdf';
$file = new File($path, true);
//write the content to the file
$file->write( $viewdata );
//return the path
return $path;
}
I need generate this pdf and send it as attacchment so, this is my code
public function publish ($id) {
$pdf_file = $this->generate( (int)$id );
$Email = new CakeEmail();
$Email->from(array('info#.....com' => '......'));
$Email->to('....#gmail.com');
$Email->subject('Nuovo ordine');
$filepath = WWW_ROOT . 'ordini/' . $id . '.pdf';
$Email->attachments(array('Ordine.pdf' => $filepath));
$Email->send('......');
}
The first time i run this code the email doesn't works, the email works nice only if the pdf is alredy in the folder.
I think that File::write perform some kind of async writing and when system execute Email::attachments the file ins't ready.
How can i insert a while() in this code to check file avability?
thanks a lot.
if($file->write( $viewdata ))
{
return $path;
}
using the return value wasn't enough.
I changed this line
$file = new File($path, false);
Opening file without forcing worked for me.