Is there a way to upload Images using Laravel Jobs - php

I am trying to upload image in laravel jobs but i keep getting this error "Serialization of 'Illuminate\\Http\\UploadedFile' is not allowed"
In my controller i try to save the image to wasabi cloud and then passing it to the job by doing this
public function store(ThreadRequest $request)
{
$imageName = time().'.'.$request->attachment->extension();
$request->attachment->storeAs('public/attachments', $imageName, 'wasabi');
$this->dispatch(CreateThread::fromRequest($request, $imageName));
return redirect()->route('threads.index');
}
And then in my job i accept $imageName as attachment and did this
public function handle(): Thread
{
$thread = new Thread([
'title' => $this->title,
'body' => Purifier::clean($this->body),
'category_id' => $this->category,
]);
$thread->authoredBy($this->author);
$thread->save();
return $thread;
}
}
I tried passing the image from my controller to my job, although i know you need to save the image temp and pass it to laravel job but that's where i am confused.
Any help would be appreciated.

Related

Laravel viewing picture in local disk

I am making like a dropbox clone for a school project, i made an upload fuction that uploads to the local disk so it cant be accessed by everyone.
Upload Function
public function updatedUpload($upload){
$object = $this->currentTeam->objects()->make(['parent_id' => $this->object->id]);
$object->objectable()->associate(
$this->currentTeam->files()->create([
'name' => $upload->getClientOriginalName(),
'size' => $upload->getSize(),
'path' => $upload->storePublicly('files', ['disk' => 'local'])
])
);
$object->save();
$this->object = $this->object->fresh();
}
But I want to put it in an in the home.blade.
How do I make this and only the person who uploaded it can access it?
You can create a specific link for the user that can see this resource.
For example in your routes/web.php
Route::get('/private_resource',[\App\Http\Controllers\PrivateResource::class, 'getLocalResource'])
->name('get_private_resource')->middleware('auth');
Define PrivateResource controller
class PrivateResource
{
public function getLocalResource($filename){
// Get your resource, for example
$file = File::where('name', $filename)->first();
// Check whether user can access this resource
// For example
if(\Auth::id() != $file->user_id) abort(403);
return \Storage::disk('local')->download($filename);
}
}
Extra: If you want extra privacy, you can use signed route using below function.
\URL::signedRoute('get_private_resource');
And add signed middleware to your route
Route::get('/private_resource',[\App\Http\Controllers\PrivateResource::class, 'getLocalResource'])
->name('get_private_resource')->middleware('auth','signed');

Laravel 5.4 file upload validation fails for python files

I'm trying to figure out what is wrong with my validation, but I'm not sure.
I have created a file upload that uploads the file to S3. Works fine except when I need to validate python files.
In my FileUploadController.php I have a store(FileStoreRequest $request) method that handles the upload. I added the $validatedData = $request->validate(); in it and it works.
I have also added the mimes.php in config folder with the following:
<?php
return [
'zip' => array('application/x-zip', 'application/zip', 'application/x-zip-compressed'),
'py' => array('text/plain', 'application/x-python' , 'application/octet-stream, application/x-python-code, text/x-python-script', 'text/x-python'),
];
And the rules() method inside my FileStoreRequest class is
public function rules()
{
return [
'preprocessor' => 'mimes:py',
];
}
Any time I try to upload the python file I get the error
The preprocessor must be a file of type: py.
When I remove the mimes check from the rules() it passes.
The rules work, because I tested it on another view for zip file upload.
Any ideas what could be wrong?
You can create custom validation like:
$input = $request->all();
if (isset($input["preprocessor"]) && !empty($input["preprocessor"])) {
$filesource = $input["preprocessor"];
$fileExtension = $filesource->getClientOriginalExtension();
$input["ext"] = $fileExtension;
}
$rules = array(
'ext' => 'nullable|in:py',
);

Laravel get path of saved file from upload

I have a laravel upload for file (along with other data that is passed to the database) Everything works. But I just can't figure out how to save the path of the file that is saved.
Here is my controller function:
public function store(Request $request)
{
request()->validate([
'name' => 'required',
'logo' => 'nullable',
'original_filename' => 'nullable',
]);
//This is where the file uploads?
if ($request->hasFile('logo')) {
$request->file('logo')->store('carrier_logo');
$request->merge([
'logo' => '',//TODO: get file location
'original_filename' => $request->file('logo')->getClientOriginalName(),
]);
}
Carrier::create($request->all());
return redirect()->route('carriers.index')->with('toast', 'Carrier created successfully.');
}
The thing I want to achieve:
I want logo to fill with something like carrier_logo/ZbCG0lnDkUiN690KEFpLrNcn2exPTB8mUdFDwAKN.png
The thing that happened every time I tried to fix it was that it placed the temp path in the database. Which ended up being something in the PHP install directory.
Just assign result to variable:
$path = $request->file('logo')->store('carrier_logo');
According to docs
Then you can do with $path variable whatever you want.
just assign the value like this.
$location=base_path('img/'.$filename);
and save it in db.
You could do this:
For FileName
$fileName = $request->file('test')->getClientOriginalName();
OR
$fileName = $request->user()->id.'.'.$request->file('logo')->getClientOriginalExtension();
$imageDirectory = 'logo_images';
$path = $request->file('logo')->storeAs($imageDirectory, $fileName);
dd($path);

Laravel form request validation priority

In my Laravel 5.6 app, I have a controller with a store method:
use Intervention\Image\Facades\Image as ImageHandler;
public function store(StoreFoo $request)
{
if ($request->hasFile('image')) {
$toResize = ImageHandler::make($request->validated()->file('image')->getRealPath());
}
}
My StoreFoo class validates that the image field is an image:
public function rules()
{
return [
'image' => 'image'
];
}
I would expect that when I try to upload a file which is not an image, the validator would catch it and return an error. Instead the code inside the store method is run, which produces an "Unsupported image type" exception from Intervention.
Why does the validator not catch this beforehand, and how can I make it work this way?
Try this in your request file:
'image' => 'nullable|file|mimes:jpeg,png,jpg',
Of course, feel free to add whatever other mimes you will accept.

Yii: How to make Dropzone Extension work?

I'm trying to add Dropzone Extension to my application in Yii, which allows asynchronous file uploading. http://www.yiiframework.com/extension/yii-dropzone/
The first thing i did was putting the downloaded folder called "dropzone" into my extensions folder "C:\xampp\htdocs\site\protected\extensions".
And here is my code for the action in the controller (MainController.php)
public function actionUpload()
{
$test = rand(100000, 999999); //TEST
var_dump($test);
$model = new UploadFile;
if(isset($_FILES['images'])){
$model->images = CUploadedFile::getInstancesByName('images');
$path = Yii::getPathOfAlias('webroot').'/uploads/';
//Save the images
foreach($model->images as $image)
{
$image->saveAs($path);
}
}
$this->render('upload', array('model' => $model));
}
the view (upload.php)
<?php
$this->widget('ext.dropzone.EDropzone', array(
'model' => $model,
'attribute' => 'images',
'url' => $this->createUrl('file/upload'),
'mimeTypes' => array('image/jpeg', 'image/png'),
'options' => array(),
));
?>
and the model (UploadFile.php)
<?php
class UploadFile extends CFormModel
{
public $images;
public function rules(){
return array
(
array(
"images",
'file',
'types' => 'jpg,gif,png',
),
);
}
}
When I run it I can see the Dropzone interface and I can add images dragging them or selection them from the file explorer.
It appears their respective progress bar and a success mark, but nothing appear in the directory of uploads, and any error is shown neither in the IDE (Netbeans) nor in the Chrome console.
I did some print tests and I realize that the code inside the 'actionUpload' is being executed only the first time (when it draws the view), but when its called from the dropzone widget it do nothing.
I'd really appreciate if you have a solution for this. I'd love if someone could give me a simple working example of this extension. Thanks.
As I understand, dropzone uploads files one by one, not all together. So $model->images holds only one image object. And foreach cycle fails.

Categories