using S3 Laravel8 create a unique folder with every upload file - amazon-s3

I have this code is working perfectly fine, But I want when I upload the image 1st time to create a new folder and store the image, as I want 2nd time when I upload a new file to create a new unique folder and store the file...
Please help me with this if someone knows how to do this because I am new to Laravel.
public function storemultipleImages(Request $request)
{
$this->validate($request, ['image' => 'required|image']);
if ($request->hasfile('image')) {
$file = $request->file('image');
$name = time() . $file->getClientOriginalName();
$filePath = 'poster_art_1/' . $name;
Storage::disk('s3')->put($filePath, file_get_contents($file));
return back()->with('success', 'Image Uploaded successfully');
}
}

Related

laravel Can't write image data to path (/app/public/uploads/profile/_6371539659671.jpg) railway.app

I tired to solve this problem
I have this code and its works in localhost.
public function test(Request $request){
if ($request->hasFile('file'))
{
$image = $request->file;
$filename = '_'.uniqid(). "." . $image->getClientOriginalExtension();
$src = 'uploads/profile/'.$filename;
Image::make($image)->save(public_path($src));
return $src;
}
}
but in production didn't work and laravel Can't write image data to path (/app/public/uploads/profile/_6371539659671.jpg) appears.
I deploy it in https://railway.app/ by my GitHub repository.
how can I solve this error?!
I trying store image by Intervention \ Image
but (/app/public/uploads/profile/_6371539659671.jpg) appears.

Fileinput issue in ActiveForm when updating via Yii 2

I am using Yii2 framwork. My file upload function worked well when I upload a single img, while when I click the posed article and I only want to update the post again(Suppose I didn't want to update the img, I only want to update other contents). But I found my uploaded file were replaced with an empty value(varchar type) when I click view. my uploaded img can't show out.
I do tried to fixed by myself as below, But the existing file value can't be saved when I click the submit button.
<?php
if (($post->file) != "") {
echo $form->field($post, 'file')->textInput()->hint('My currently uploaded file')->label('My Photo') ;
}
else{
echo $form->field($post, 'file')->fileInput()->hint('To upload a new file')->label('My Photo') ;
}
?>
When I click submit button, my existing file was gone.
Is there any good way to fix it.
Thanks for your opinions in advance.
Use another variable in your model for upload a file.
For example use file_field name for get file from submitted and store in file field.
class PostModel extends Model
{
/**
*
* #var UploadedFile
*/
public $file_field;
public function rules() {
return [
['file_field', 'file'],
];
}
}
echo $form->field($post, 'file_field')->fileInput()->hint('To upload a new file')->label('My Photo') ;
$post->file_field = UploadedFile::getInstance($post, 'file_field');
For upload new file check the file_field:
if ($post->file_field) {
// $post->file old file
// Save $post->file_field and store name in $post->file
}
Add a rule to your model rules:
[['file'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg'],
and check for an empty upload in your controller:
if (Yii::$app->request->isPost) {
$ok = true;
// process your other fields...
...
// process image file only if there is one
$post->file= UploadedFile::getInstance($post, 'file');
if ($post->file && $post->upload()) {
}
if ($ok) {
return $this->redirect(...);
}
}
See Yii2 docs and the Yii2 guide for detailed infos about file upload.

Laravel 7 change where file uploads to

I have a file upload form in on of my blade files.
However when I upload the file I see its saving the file to /storage//Applications/MAMP/tmp/php/phpIVfP2L.mp4 how do I set this upload to be saved to a specific location like I want them saved in the Laravel public folder that is in the Laravel root directory so the path would be /public/trainingvideos
Below is my controller code where my file upload code is
public function addtraining(Request $req) {
//Save to a mysql database
//print_r($req->input());
$pwdata = new AddTraining;
$pwdata->userid = $req->userid;
$pwdata->video_title = $req->trainingtitle;
$pwdata->video_description = $req->trainingdesc;
$pwdata->video_url = $req->trainingvideo;
if($req->hasFile('trainingvideo')) {
// Let's do everything here
if($req->file('trainingvideo')->isValid()) {
//
$validated = $req->validate([
'trainingvideo' => 'mimes:mp4,mov|max:10000',
]);
$extension = $req->trainingvideo->extension();
$req->trainingvideo->storeAs('public_path()/public/trainingvideos', $req->trainingvideo.".".$extension);
$url = Storage::url($req->trainingvideo.".".$extension);
$pwdata->video_url = $url;
//Session::flash('success', "Success!");
}
}
//abort(500, 'Could not upload video :(');
$pwdata->save();
The /tmp directory is where files are temporarily stored when uploaded.
In your controller you need to go about actually storing that file, the docs cover this in depth; https://laravel.com/docs/7.x/requests#storing-uploaded-files
It's worth mentioning that if you leave the files in your tmp directory, they will be garbage collected at some point and so this is not a safe location to store files.

Laravel 5 issues uploading/saving pdf

I'm using Laravel 5.6, jQuery 3.3.1, bootstrap 3.3.7, and PHP 7.1.4
I need to be able to allow users to upload files and pictures, basically jpg, gif, png, and pdf. I am using the public disk and storing the files in storage/app/public/folder_name where folder_name is defined in an env file
FILESYSTEM_DRIVER=public
PO_FILE_FOLDER=purchase_orders
INSURANCE_FILE_FOLDER=insurance
NOTE_FILE_FOLDER=notes
RENTAL_AGREEMENT_FILE_FOLDER=rental_agreements
SIGNATURES=signatures
They are then defined in config/app
'insurance_file_folder' => env('INSURANCE_FILE_FOLDER', ''),
'po_file_folder' => env('PO_FILE_FOLDER', ''),
'note_file_folder' => env('NOTE_FILE_FOLDER', ''),
'rental_agreement_file_folder' => env('RENTAL_AGREEMENT_FILE_FOLDER', ''),
'max_image_width' => env('MAX_IMAGE_WIDTH', 500),
'filesystem_driver' => env('FILESYSTEM_DRIVER', 'local'),
When I upload image files they upload to the appropriate folder but when I try to upload pdf files the system creates a new folder named as what I'm naming the file and the pdf is in the new folder with a random name. I'm using the exact same code to upload both images and pdf files so I can't figure out why it works for one but not the other.
Here is my controller code
public function store(PurchaseOrderRequest $poRequest, Customer $customer)
{
$purchaseOrder = $customer->purchaseOrders()->create($poRequest->except('attachment'));
if ($poRequest->hasFile('attachment')) {
$purchaseOrder->saveFile(config('app.po_file_folder', ''), $poRequest->file('attachment'));
}
return redirect()->action('CustomerController#edit', $customer)->with('alert', 'Purchase Order created.');
}
My model PurchaseOrder saveFile code
public function saveFile($folder_name, $file)
{
// if file submited then check if file already exists, if so delete file and create new file
$file_name = $this->createFileName();
File::removeFiles($folder_name.'/'.$file_name, FALSE);
$file_name = $file_name.'.'.$file->getClientOriginalExtension();
$file = File::resize($file);
$this->attachment_path = $folder_name.'/'.$file_name;
Storage::disk(config('app.filesystem_driver', ''))->put($this->attachment_path, $file);
$this->save();
}
public function createFileName()
{
$file_name = 'po_'.$this->customer->code.'-'.$this->customer->id.'_'.$this->po_number.'-'.$this->id;
return $file_name;
}
My File helper code
public static function resize($file)
{
$resized_file = $file;
if (strtolower($resized_file->getClientOriginalExtension()) != 'pdf') {
// resize file if it is not pdf (file is photo)
// get image size then resize largest size to size limit - dont upsize if image is smaller than max size
list($width, $height) = getimagesize($resized_file);
if ($width > $height) {
$resized_file = Image::make($resized_file)->resize(config('app.max_image_width', ''), null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
})->encode($resized_file->getClientOriginalExtension(), 60);
} else {
$resized_file = Image::make($resized_file)->resize(null, config('app.max_image_width', ''),function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
})->encode($resized_file->getClientOriginalExtension(), 60);
}
}
return $resized_file;
}
public static function removeFiles($file_name, $ext_included = FALSE)
{
if ($ext_included == TRUE) {
// remove specific file
if (Storage::disk(config('app.filesystem_driver', ''))->exists($file_name)) {
Storage::delete($file_name);
}
} else {
// remove file with any extension
$ext = array('.pdf', '.jpg', '.jpeg', '.gif', '.png');
for ($cnt = 0; $cnt <= 4; ++$cnt) {
if (Storage::disk(config('app.filesystem_driver', ''))->exists($file_name.$ext[$cnt])) {
Storage::delete($file_name.$ext[$cnt]);
}
}
}
}
I realize the code may be a little confusing use the env variables but I'm trying to limit the pain in the event I need to change the folder name or move the files outside of the app. The application will have very few users maybe 3 or 4 and I don't anticipate a lot of files being uploaded which is why I'm storing the files in the application structure.
This is my first Laravel app and I put this code together using the docs and many a many different tutorials. It took a while but eventually I got it to work for images. So if you see things that don't look standard or good practice I welcome any pointers.
Thanks for taking the time to read this, any help is appreciated!
I had to use two different approaches to saving files in the system based on if the file was an image or pdf. I do some processing (resizing) on images before putting them into my storage folders with Intervention Image. This in turn returns a different object type than the raw uploaded file, because of this some of the commands to add the file (after processing) will not work.
So if I'm storing a pdf file I use:
$file->storeAs($folder_name, $file_name, config('app.filesystem_driver', ''));
If I'm storing an image that I have used Intervention Image on then I use:
Storage::disk(config('app.filesystem_driver', ''))->put($this->attachment_path, $file);
I couldn't find one command that worked for both so I just check the extension before storing. Not sure if this is the "right way" but it got the job done.

HTML compresson in zend

I am new to zend. I am using gzip compression for my website. For this I have done the setting in php.ini for this. It is working fine.
Now the issue is, before compressing the html or better to say the response I want to remove all the blank spaces and new lines from the html, so that it will be compressed and then I will apply the gzip compression.
Now my question is - that when i am using the following plugin :
class My_Plugin_Plugin extends Zend_Controller_Plugin_Abstract {
public function postDispatch(Zend_Controller_Request_Abstract $request)
{
$response = $this->getResponse();
$body = $response->getBody();
$body = preg_replace('|\s+|', '', $body);
header('Content-Encoding: gzip');
$response->setBody($body);
}
}
,I get only the page view content, but it did not show the content of layout. How can i get the whole content of the page including layout content
You can use a controller plugin and hook up the postDispatch method and manipulate the response from there.
class MyPlugin extends Zend_Controller_Plugin_Abstract
{
public function postDispatch(Zend_Controller_Request_Abstract $request)
{
$response = $this->getResponse();
$body = $response->getBody();
$body = preg_replace('|\s+|', '', $body);
$response->setBody($body);
}
}
Somewhere in your bootstrap:
$front = Zend_Controller_Front::getInstance();
$front->setControllerDirectory('/path/to/controllers')
->setRouter(new Zend_Controller_Router_Rewrite())
->registerPlugin(new MyPlugin());
$front->dispatch();
Note: since the space would get compressed anyway I don't think it's really worth the trouble