I am wondering what to write in my laravel controller to allow me work with a pdf document posted from the front end by an AJAX request. I have found code online to check if an image is uploaded, but anyone have an idea what I need to do if it's a pdf document.
Please see my code below.
public function postUpload() {
$file = Input::file('image');
do something here.....
}
An example from documentation:
public function postUpload(Request $request) {
if ($request->hasFile('file')) {
$file = $request->file('file');
do something here.....
}
}
To check if file is PDF, use validation rules, like:
$rules = [
"file" => "mimes:pdf"
]
Related
The project works fine on my localhost but has issues on a live shared server.
I have tried adding this code to my index.php
// set the public path to this directory
$app->bind('path.public', function() {
return __DIR__;
});
I have tried adding this code in a new sym.php file in my public folder
<?php
$targetFolder = $_SERVER['DOCUMENT_ROOT'].'/storage/app/public';
$linkFolder = $_SERVER['DOCUMENT_ROOT'].'/public/storage';
symlink($targetFolder,$linkFolder);
echo 'Symlink process successfully completed';
?>
I have tried adding this on my web.php and then running site/linkstorage
Route::get('/linkstorage', function () {
Artisan::call('storage:link');
});
None of these solutions works
here is a snippet of my Controllers code:
public function storeBrand(Request $request){
$this->validate($request, ['brand_name'=> 'required',
'brand_url'=> 'required',
'brand_image'=>'image|nullable|max:1999']);
if($request->hasFile('brand_image')){
//1 : get filename with ext
$fileNameWithExt = $request->file('brand_image')->getClientOriginalName();
//2 : get just file name
$fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
//3 : get just extension
$extension = $request->file('brand_image')->getClientOriginalExtension();
//4 : file name to store
$fileNameToStore = $fileName.'_'.time().'.'.$extension;
//upload image
$path =$request->file('brand_image')->storeAs('public/BrandImages', $fileNameToStore);
}
else{
$fileNameToStore ='noimage.jpg';
}
$brand=new Brand();
$brand->brand_name =$request->input('brand_name');
$brand->brand_url =$request->input('brand_url');
$brand->brand_image =$fileNameToStore;
$brand->save();
return redirect('/create_brand')->with('status', 'The '.$brand->brand_name.' Brand has been saved successfully. Create another one.');
Note
When an image is uploaded the path can be traced, but the image is not found, returns an empty image.
Thank you for your time and assistance.
I have got the solution:
I Wrote down this code in my web.php route file:
Route::get('/linkstorage', function () { $targetFolder = base_path().'/storage/app/public'; $linkFolder = $_SERVER['DOCUMENT_ROOT'].'/storage'; symlink($targetFolder, $linkFolder); });
After that I navigated to my url/linkstorage
It worked!!
Looking at the code in your controller, it seems correct. Perhaps the error is within your form in the Blade file associated with this method. Based on experience I tend to forget to write this and this could probably sort out your error.
Write this on the form tag.
<form action="{{ insert the route here }}" method="POST" enctype="multipart/form-data">
// insert form input fields here...
</form>
i want to validate my file, only .ico files.
Laravel dont include x-icon mime I think, how can i validate it?
$logo = $request->file('logo');
$favicon = $request->file('favicon');
$request->validate([
'logo'=>'image|mimes:png',
'favicon'=>'',
]);
Make a custom validation rule as explained here.
In short:
First do:
php artisan make:rule CheckIfFavicon
Then:
Create the validation code in the created Rules-file.
Try something like:
public function passes($attribute, $value)
{
return $value->getClientOriginalExtension() == 'ico';
}
Then ad it to the validation. Note, that if you make a custom validation class you will have to change the syntax in the $request->validate([...]) from pipe-ing to array.
$request->validate([
'favicon' => [new CheckIfFavicon],
]);
use $file->getClientOriginalExtension() in code if you only want to check file extension
$ext = $file->getClientOriginalExtension();
if($ext == 'ico'){
//uploadfile
}else{
//do something else
}
use this as reference.
I want to upload a file in Laravel:
I put this code in route
Route::post('upload', 'myconttest#test')->name('upload');
And put this code in controller
function test(Request $request){
$file=$request->file('myfile');
$filename=$file->getClinetOriginalName();
// $projectname;
$path='files/';
$file->move($path,$filename);
}
I create a folder in public called files. The code runs without error but the file is not saved.
Its a working code please see this
public function store(Request $request)
{
$checkval = implode(',', $request->category);
$input = $request->all();
$input['category'] = $checkval;
if ($request->hasFile('userpic')) {
$userpic = $input['pic'];
$file_path = public_path("avatars/$userpic");
if(File::exists($file_path)) {
File::delete($file_path);
}
$fileName = time().$request->userpic->getClientOriginalName();
$request->userpic->move(public_path('avatars'), $fileName);
$input['userpic'] = $fileName;
Product::create($input);
return redirect()->route('productCRUD.index')->with('success','Product created successfully');
}
}
Make sure your form is enabled to upload the file. So check that the following attribute is set or not.
<form action"" 'files' => true>
Use the following namespace
use Illuminate\Support\Facades\Input;
Then try this:
$file = Input::file('myfile');
$filename = $file->getClinetOriginalName();
move_uploaded_file($file->getPathName(), 'your_target_path/'.$filename);
I think you can try this:
First you give folder permission to files folder in public folder
function test(Request $request){
$file=$request->file('myfile');
$filename=$file->getClinetOriginalName();
$file->move(public_path().'/files/', $filename);
}
Hope this work for you !!!
In controller test function you need to given public path of files folder like
$path = public_path('files/');
for moving file on given public folder path.
I have a requirement to upload a document to server, since it is a personal one, they want it to be uploaded outside public folder. I know how to upload a file:
if ($model->load(Yii::$app->request->post())) {
$model->document = UploadedFile::getInstance($model, 'document');
if ($model->upload() !== false) {
$model->save();
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
But how do I read it since a Url will not be able to access it? I was planning to create an action to get the file but not sure if Yii has something ready for this case?
Yes Yii can send file output, but you still have to create your own action.
Lets assume following code in siteController Specific to image output, You can use same way to output other files.
public function actionImage($image_path) {
Yii::$app->getResponse()->sendFile(Yii::getAlias('#image_uploads') . $image_path);
}
now image src will be something like
<img src="/site/image?image_path=/posts/1.png" /> or equivalent to the real application url routes
So basic function to send file output by Yii2 is
Yii::$app->getResponse()->sendFile();
Located Under
\yii\web\Response.php
I need to send an image to server via an ajax request and it gets through just fine
and in my controller I can just use $_FILES["image"] to do stuff to it.
But I need to validate the image before I save it.
And in the Yii this can be achieved by doing something like this
$file = CUploadedFile::getInstance($model,'image');
if($model->validated(array('image'))){
$model->image->saveAs(Yii::getPathOfAlias('webroot') . '/upload/user_thumb/' . $model->username.'.'.$model->photo->extensionName);
}
But the problem is I don't have a $model, all I have is $_FILES["image"], now what should I put instead of the $model???
is there any other way where I can validate and save files without creating a model and just by Using $_FILES["image"]?
thanks for this awesome community... :)
Exists many ways how you can do upload. I want offer to you one of them.
1.You need to create model for your images.
class Image extends CActiveRecord {
//method where need to specify validation rules
public function rules()
{
return [
['filename', 'length', 'max' => 40],
//other rules
];
}
//this function allow to upload file
public function doUpload($insName)
{
$file = CUploadedFile::getInstanceByName($insName);
if ($file) {
$file->saveAs(Yii::getPathOfAlias('webroot').'/upload/user_thumb/'.$this->filename.$file->getExtensionName());
} else {
$this->addError('Please, select at least one file'); // for example
}
}
}
2.Now, need to create controller, where you will do all actions.
class ImageController extends CController {
public function actionUpload()
{
$model = new Image();
if (Yii::app()->request->getPost('upload')) {
$model->filename = 'set filename';
$insName = 'image'; //if you try to upload from $_FILES['image']
if ($model->validate() && $model->doUpload($insName)) {
//upload is successful
} else {
//do something with errors
$errors = $model->getErrors();
}
}
}
}
Creating a model might be overkill in some instances.
The $_FILE supervariable is part of the HTTP mechanism.
You can handle the copy by using the native PHP function move_uploaded_file()
$fileName = "/uploads/".myimage.jpg";
unlink($fileName);
move_uploaded_file($_FILES['Filedata']['tmp_name'], $fileName);
However, you lose the niceties of using a library that provides additional functionality and checks (eg file type and file size limitations).