Laravel file upload creates folder with a temp file - laravel-5

I'm trying to get my application to upload files to "public/uploads/documentos/{the-id}" but can't figure out what's wrong with my current setup. Right now, if I upload a file called "myfile.pdf", it creates a folder named "myfile.pdf" and inside of it a *.tmp file. In my database, "{the-id}/myfile.pdf" is saved as the file url but this takes me to the folder view, when what I want is to see the file inside of it.
How can I change it so that when a document is upload, it creates the file "myfile.pdf" directly under "public/uploads/documentos/{the-id}" so that I can access it like that? {the-id} is a folder created based on the patient's id, so all documents belonging to them are saved to the same folder.
Controller
public function store(Request $request)
{
$this->validate($request, [
'tipo' => 'required|max:100',
'descripcion' => 'max:200',
'fecha_documento' => 'max:20',
'archivo' => 'required|mimes:doc,docx,pdf,jpg,png,jpeg',
'mascota_id' => 'required',
'mascota_num' => 'required',
]);
$documento = new Documento;
$documento->mascota_num = $request->input('mascota_num');
$documento->mascota_id = $request->input('mascota_id');
$documento->tipo = ucfirst($request->input('tipo'));
$documento->descripcion = ucfirst($request->input('descripcion'));
$documento->fecha_documento = $request->input('fecha_documento');
if($request->hasFile('archivo')) {
$archivo = $request->file('archivo');
$archivo_folder = public_path('/uploads/documentos/') . $request->input('mascota_num');
$archivo_nombre = $archivo->getClientOriginalName();
$archivo_url = $archivo_folder . '/' . $archivo_nombre;
if (file_exists($archivo_folder)) {
$archivo->move($archivo_folder . '/' . $archivo_nombre);
} else {
File::makeDirectory($archivo_folder, $mode = 0777, true, true);
$archivo->move($archivo_folder . '/' . $archivo_nombre);
}
$documento->archivo = $request->input('mascota_num') . '/' . $archivo_nombre;
$documento->save();
return redirect()->route('mascotas.show', [$request->input('mascota_num')])->with('message', 'Documento agregado exitosamente.');
}
}
How my uploaded files look with this code:
uploads/documentos/
-- 1
-- file.pdf /folder
-- random_name.tmp /file
-- 2
-- file.pdf /folder
-- random_name.tmp /file
-- otherfile.pdf /folder
-- random_name.tmp /file
}
What I want
uploads/documentos/
-- 1
-- myfile.pdf /file
-- 2
-- myfile.pdf /file
-- otherfile.pdf /file
Ideally, I'd like to keep the files private, so I tried to upload them to the storage folder with this code:
Storage::put('documentos/'.$request->input('mascota_num').'/', $archivo_nombre);
$documento->archivo = Storage::url('documentos/'.$request->input('mascota_num').'/'.$archivo_nombre);
but {the-id} folder wasn't created and the files weren't saved, all I got was:
storage/app/documentos/
-- 1 /file without extension
-- 2 /file without extension
I'd settle for making the first part work for now. Thanks in advance for your help.

After much trial and error, I managed to upload files to the storage folder of my application.
if($request->hasFile('archivo')) {
$archivo = $request->file('archivo');
Storage::disk('documentos')->put($request->input('mascota_num') . '/' . $archivo->getClientOriginalName(), File::get($archivo));
$documento->archivo = $request->input('mascota_num') . '/' . $archivo_nombre;
$documento->save();
}
Files are saved to /storage/app/public/documentos/ under the correct patient id folder and with the correct file name.
I haven't found a way to correctly link to the files from my show blade, Storage::url('documentos/'.$documento->archivo)) shows a 404 error page, even though the file path is correct. Hopefully I can get this working next.

Related

CI4 - Trying to move image but get error "could not move file php6WkH2s to /var/www/example.com/development.example.com/app_dir/public/ ()

I am trying to upload a file and move it to public/ folder. The file uploads without problem to writable folder, however, it is the moving to the public folder that has a problem.
Here is my code;
$update_post->move(ROOTPATH.'public/', $update_post.'.'.$fileType);
Path is correct. When I echo out echo ROOTPATH.'public/'; and then manually copy/paste, I do get to the destination directory.
Permissions correct. There are my permission on the public/ directory:
drwxr-xr-x 9 www-data www-data 4096 Jan 30 01:08 public
Any hints appreciated.
Reason:
It's because the move(string $targetPath, ?string $name = null, bool $overwrite = false) method's $name argument is invalid.
$update_post->move( ... , $update_post.'.'.$fileType);
Explanation:
Concatenating an class CodeIgniter\Files\File extends SplFileInfo instance calls the inherited SplFileInfo class's __toString() method which returns the path to the file as a string.
Note that it doesn't return the filename, which is what you're interested in.
Solution:
You should instead pass in the basename instead.
$update_post->move(
ROOTPATH . 'public/',
$update_post->getBasename()
);
Alternatively, since you're not changing the destination filename, it's cleaner to just not pass in the second parameter of the move(...) method. I.e:
$update_post->move(
ROOTPATH . 'public'
);
Addendum:
If you wish to change the destination filename to a new name, try this instead:
guessExtension()
Attempts to determine the file extension based on the trusted
getMimeType() method. If the mime type is unknown, will return null.
This is often a more trusted source than simply using the extension
provided by the filename. Uses the values in app/Config/Mimes.php to
determine extension:
$newFileName = "site_logo"; // New filename without suffixing it with a file extension.
$fileExtension = $update_post->guessExtension();
$update_post->move(
ROOTPATH . 'public',
$newFileName . (empty($fileExtension) ? '' : '.' . $fileExtension)
);
Notes:
The move(...) method returns a new File instance for the relocated file, so you must capture the result if the resulting location is needed: $newRelocatedFileInstance = $update_post->move(...);

Laravel Storage not storing created PDF files

I am facing an issue where my created PDF's are not being stored in laravel.
I have the following set in my filesystems.php under the disks tag
'completedforms' => [
'driver' => 'local',
'root' => storage_path('app/storage/completedforms'),
],
In my controller I have the following:
$pdf = PDF::loadView('report.form19', compact('generalreport','monthlyRoll', 'nightsInMonth', 'groupfee', 'subs', 'wing','weeksinmonth', 'meetingnights', 'lastRollMap', 'month_name', 'totalmember', 'totalcadets', 'totalnco', 'totalto', 'totalofficer'));
Storage::disk('completedforms')->put('Form 19 - '.$month_name . ' ' . $lastRollMap->roll_year.'.pdf', $pdf->output());
return $pdf->download ('Form 19 - '.$month_name . ' ' . $lastRollMap->roll_year.'.pdf');
I have added use Illuminate\Support\Facades\Storage; to my Controller
The pdf is created and downloads no issues, however the file is not being saved in the located as difined for the disk in the filesystems.php.
I have created the folder manually to ensure it exists. I have even set the file name to test.php to remove any variables fromm the file name
storage_path already starts at: /storage,
so change it like so:
'root' => storage_path('/desired'),

Make directory inside directory Laravel 5.4

I am trying to make a directory inside a directory using the following code:
Storage::makeDirectory('app/public' . $data['code'] . '/' . 'themes', true);
So the structure will be :
Folder 1 :
app/public/123
Folder 2:
app/public/123/themes
I have been trying for the last 2 hours. I hope somebody can help. Thanks !
You can create the directories recursively by calling makeDirectory() method
overFile` object
$result = File::makeDirectory('/path/to/directory', 0775, true);
In Your case, To create the themes directory inside storage directory
Storage::makeDirectory('themes', 0775, true);
To create a file inside the public directory
$result=File::makeDirectory('app/public/' . $data['code'] . '/' . 'themes',0755, true);
dd($result);
The problem was the path structure.
The following code worked :
Storage::makeDirectory('public/' . $data['code'] . '/' . 'themes');
In your app check what the path given in config/filesystem.php on line 44. So when you trying to create directory or a file check the storage directory

How to change the loaction of compressing folder for css/js in magento

I am using potato compressor extension in my site to compress the css/js files. I am getting those css/js inside the media folder. But I want them in the skin folder. Is there a way to change the location of compressing folder in potato compressor.
Following steps worked fine for me:
1. In File Package.php:
app/code/local/Potato/Compressor/Model/Design/Package.php
function getMergedJsUrl($files):
Change:
return Mage::getBaseUrl('media', Mage::app()->getRequest()->isSecure()) . $filePath . '/' . $targetFilename;
To:
return Mage::getBaseUrl('skin', Mage::app()->getRequest()->isSecure()) . $filePath . '/' . $targetFilename;
function getMergedCssUrl($files):
Change:
$baseMediaUrl = Mage::getBaseUrl('media', $isSecure);
To:
$baseMediaUrl = Mage::getBaseUrl('skin', $isSecure);
2. In File Package.php:
app/code/core/Mage/Core/Model/Design/Package.php
Change 'media' to 'skin' at all locations.
3. In File Package.php:
app/code/local/Potato/Compressor/Helper/Data.php
function getRootCachePath()
Change:
return Mage::getBaseUrl('media') . self::MAIN_FOLDER;
To:
return Mage::getBaseDir('skin') . DS. self::MAIN_FOLDER;
function getRootCacheUrl()
Change:
return Mage::getBaseUrl('media') . self::MAIN_FOLDER;
To:
return Mage::getBaseUrl('skin') . self::MAIN_FOLDER;
NOTE IN case if you have override the Potato/Compressor/Model/Design/Package.php then update that method with this:
In File Package.php:
app/code/local/Your_Theme/Navigation/Model/Compressor/Design/Package.php
function getMergedJsUrl($files):
Change:
return Mage::getBaseUrl('media', Mage::app()->getRequest()->isSecure()) . $filePath . '/' . $targetFilename;
To:
return Mage::getBaseUrl('skin', Mage::app()->getRequest()->isSecure()) . $filePath . '/' . $targetFilename;
function getMergedCssUrl($files):
Change:
$baseMediaUrl = Mage::getBaseUrl('media', $isSecure);
To:
$baseMediaUrl = Mage::getBaseUrl('skin', $isSecure);
Clear your magento and browser cache and js/css cache. Check the url of po_compressor file path by going to source of your site code, that will change to skin/ instead of media/
There is a config option Cache Directory under JS/CSS Compressor settings.
It becomes visible after enabling whether Merge JavaScript files or Merge CSS files option.
There are three possible values:
Media
Skin
Js

How to delete a file in laravel 4

I'm using laravel 4 and I need to change an uploaded image, I have it in:
Public
--uploads
---news
----id_news.jpg
When editing the new's I want to make a change image form, but how could I delete and upload another file. I am using:
Input::file('img')->move('uploads/news', $id.'_news.jpg');
The problem it's that it doesn't work, it's not replacing the file, so how could I delete The image so I could upload again.
In laravel 3 I only used:
File::delete('path/to/file');
But I don't see anything about removing files in laravel docs.
I think you should append public_path() to file names , to get real file path, like this
File::delete(public_path().$id.'_news.jpg');
There is still the delete method in Laravel 4:
src/Illuminate/Filesystem/Filesystem.php
otherwise just use good old unlink()!?
You can easily do something like:
$filename = public_path().'/uploads/foo.bar';
if (File::exists($filename)) {
File::delete($filename);
}
Reference: Laravel-recipes Delete a File
Other delete usage:
// Delete a single file
File::delete($filename);
// Delete multiple files
File::delete($file1, $file2, $file3);
// Delete an array of files
$files = array($file1, $file2);
File::delete($files);
Source: http://laravel-recipes.com/recipes/133/deleting-a-file
$destinationPath = 'uploads/my-image.jpeg'; // from public/
if ( File::exists($destinationPath) ) {
File::delete($destinationPath);
}
This works on laravel 4.2.
File::delete(storage_path()."/ProductSalesReport-20150316.csv");
// Here are some other paths to directories laravel offers, Hope this
helps
/* Path to the 'app' folder */
echo app_path();
/* Path to the project's root folder */
echo base_path();
/* Path to the 'public' folder */
echo public_path();
/* Path to the 'app/storage' folder */
echo storage_path();

Resources