File uploads in Laravel - php

I'm just starting out with Laravel and trying to get file uploads working using Dropzone JS. I can upload files successfully, but they're landing in app/Http/Controllers, where they're not then publicly accessible.
It seems to be treating this directory as the root, so if I specify /uploads as the folder then they'll go in app/Http/Controllers/uploads (which is obviously no good either). Using ..s doesn't seem to have any effect.
This is my store method for the file uploads:
$ds = DIRECTORY_SEPARATOR;
$storeFolder = '';
if ( ! empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
$targetFile = $targetPath. $_FILES['file']['name'];
move_uploaded_file($tempFile,$targetFile);
}
I've also tried a number of other methods I found (below) but I get 500 errors in Chrome's element inspector with those.
From official docs
$path = $request->file('file')->store('uploads');
From a tutorial I found
$file = $request->file('file');
$destinationPath = '/';
$file->move($destinationPath,$file->getClientOriginalName());
From another tutorial
$uploadedFile = $request->file('file');
$filename = time().$uploadedFile->getClientOriginalName();
Storage::disk('local')->putFileAs(
'/'.$filename,
$uploadedFile,
$filename
);
The current method seems fine but just needs to store files in public/uploads.

Use this path instead:
$targetPath = public_path().'/uploads/';

I also suggest making a perfect route for our storage path so when someone adds hostname/storage it will not show your directory to someone only files can be accessible
Route::get('storage/{filename}', function ($filename)
{
$path = storage_path('public/' . $filename);
if (!File::exists($path)) {
abort(404);
}
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
});

Related

How to upload a image using Slim Framework

I want to storage a image in server and save the path in MySQL, but i'm not finding a good code to do it.
I found this, but does not work:
$container = $app->getContainer();
$container['upload_directory'] = __DIR__ . '../uploads';
$app->post('/photo', function (Request $request, Response $response) use ($app) {
$directory = $this->get('upload_directory');
$uploadedFiles = $request->getUploadedFiles();
$uploadedFile = $uploadedFiles['picture'];
if($uploadedFile->getError() === UPLOAD_ERR_OK) {
$filename = moveUploadedFile($directory, $uploadedFile);
$response->write('uploaded ' . $filename . '<br/>');
}
});
function moveUploadedFile($directory, UploadedFile $uploadedFile){
$extension = pathinfo($uploadedFile->getClientFilename(),
PATHINFO_EXTENSION);
$basename = bin2hex(random_bytes(8));
$filename = sprintf('%s.%0.8s', $basename, $extension);
$uploadedFile->moveTo($directory . DIRECTORY_SEPARATOR . $filename);
return $filename;
}
Somebody knows how to upload image and save the path in MySQL?
First you need a database connection for MySQL. Read more
Then create a table, e.g. files(id, path, filename)
To insert the record (after the upload) into the table, you could use an SQL statement as follows:
// ...
$filename = moveUploadedFile($directory, $uploadedFile);
$response->getBody()->write('File uploaded: ' . $filename);
$row = [
'path' => $directory,
'filename' => $filename
];
$sql = "INSERT INTO files SET path=:path, filename=:filename;";
$pdo->prepare($sql)->execute($row);
// ...
return $response;
Please note that $response->write('...') will not work. It must be $response->getBody()->write('my content');.
Edit: Make sure that the uploads/ directory exists and the directory has write access. For example chmod -R 1777 uploads/

Image Upload is not working in a Laravel Project hosted in a shared server

I have deployed a Laravel project in a shared hosting. I have changed my .env file and copied all files from the public folder to the main directory and deleted the public folder. Now the problem is, whenever I am trying to upload an image, I am getting an internal server error. I suppose the problem is the Image Intervention is not getting the right folder to save the image. I have tried the both ways given below:
if ($request->hasfile('admin_pro_pic')) {
$image = $request->file('admin_pro_pic');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('/images/admin/' . $filename);
Image::make($image)->resize(950, 700)->save($location);
$admin->admin_pro_pic = $filename;
}
and
if ($request->hasfile('admin_pro_pic')) {
$image = $request->file('admin_pro_pic');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = '/images/admin/' . $filename;
Image::make($image)->resize(950, 700)->save($location);
$admin->admin_pro_pic = $filename;
}
But None of these is working. Any possible Solution?
Use laravel base_path function, so your code will look like this
if ($request->hasfile('admin_pro_pic')) {
$image = $request->file('admin_pro_pic');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = base_path().'/images/admin/' . $filename;
Image::make($image)->resize(950, 700)->save($location);
$admin->admin_pro_pic = $filename;
}
Answer Update
Issue was fileinfo extension missing or disbaled.
Try This.
use Storage;
use File;
if(!empty($request->file('admin_pro_pic')))
{
$file = $request->file('admin_pro_pic') ;
$fileName = $file->getClientOriginalName() ;
$destinationPath = public_path().'/images/' ;
$file->move($destinationPath,$fileName);
$admin->image=$fileName;
}
Create imges inside public directory.
I am handling it like this:
// check for defined upload folder inside .env file, otherwise use 'public'
$publicUploadDir = env('UPLOAD_PUBLIC', 'public/');
// get file from request
$image = $request->file('admin_pro_pic');
// hasing is not necessary, but recommended
$new['path'] = hash('sha256', time());
$new['folder] = 'images/admin/';
$new['extension'] = $file->extension();
// store uploaded file and retrieve path
$image->storeAs($publicUploadDir, implode($new, '.'));

imagescale function while uploading file

I try to implement a very simple scale function while uploading the file to the server. My host has 5.5.38 php version and gd is included and is 2.1.0 version.
The upload function worked until I tried to use the scale function. Obviously I am doing the wrong way but honestly I don't know what I am doing wrong and after a lot of research i am here to ask for your help..
This is the code that i use to upload file and scale it:
$id2 = $_POST['hiddenId'];
$ds = DIRECTORY_SEPARATOR;
// CREATE DIRECTORY
$dir = "gallery/g";
$dir .= $id2;
$dir .= "/";
$dir2 = '../../' . $dir;
if (!mkdir($dir2,0777,true));
$foldername = $dir;
if (!empty($_FILES)) {
/* DATA FOR DATABASE */
$images = '';
$images .= $dir;
$images .= $_FILES['file']['name'];
/* UPLOAD FILE */
$fileupload = basename( $_FILES['file']['name']);
$fileType = $_FILES['file']['type'];
$fileSize = $_FILES['file']['size'];
$tempFile = $_FILES['file']['tmp_name'];
//$targetPath = dirname( __FILE__ ) . $ds . $foldername . $ds;
// FILE DIRECTORY
$targetPath = '../../' . $foldername;
// TRY TO SCALE IMAGE
$imagenew = ''; // NEW VARIABLE
$imagenew = imagecreatefromjpeg($tempFile); // PASSING THE TEMPFILE
$imagescaled = imagescale($imagenew, 800); // SCALING THE FILE
$targetFile = $targetPath. $imagescaled;
// MOVE SCALED FILE TO THE SERVER
move_uploaded_file($tempFile,$targetFile);
// UPDATE DATABASE
update_gallery($id2,$images,$con);
}
i inspected the code with firebug but it returns no error so I don't know where to start to catch the error.. May you help me please?

move_uploaded_file() in php returns true but file not found inside the directory

Please i need help on this.
I was uploading an image to my server using the move_uploaded_file() method, the method returns true bu the uploaded file was not found inside the specified directory on my server. i have checked thoroughly, searched for the file on the server in case it was uploaded to another directory, checked the permission on the directory but all seems perfect. i really dont know what went wrong .
Here is the snippet of the code.
$uploaddir = './upload_dir/';
$allowed = array('gif', 'png', 'jpg','bmp');
$filename = $_FILES['uploadfile']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$data = array();
if (!in_array($ext, $allowed)) {
$data['status'] = 'error';
$data['error_message'] = 'Invalid file type';
}
else{
$file_name = time() . '_' . uniqid() . '_' . basename($_FILES['uploadfile']['name']);
$file_name = preg_replace('/[^a-z0-9_\.\-]+/i', '_', $file_name);
$file = $uploaddir . $file_name;
if (isset($_FILES['uploadfile']['tmp_name']) && move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) {
$data['status'] = 'success';
$data['file_name'] = $file_name;
} else {
$data['status'] = 'error';
}
echo json_encode($data);
}
Thanks in advance.
Please use is_uploaded_file($_FILES['uploadfile']['tmp_name']) instead of isset($_FILES['uploadfile']['tmp_name']) for security reason check here
And for the upload dir use $uploaddir = $_SERVER['DOCUMENT_ROOT'] . "/upload_dir/"; instead of $uploaddir = './upload_dir/'; to get absolute path instead of relative one.
thanks everyone. I gave the wrong permission to the folder. that seems to be the problem for my own case.

How Do I Upload a File using a Laravel Package?

I have a file attachment feature in a Laravel package. I want the uploaded attachment to save in the project directory using the package and NOT within the package. Currently, the file is uploaded into the package uploads directory instead of the project uploads directory. Any suggestions on how to save this file in the right location?
Controller:
$attachment->spot_buy_item_id = $id;
$attachment->name = $_FILES['uploadedfile']['name'];
$attachment->created_ts = Carbon::now();
$ds = DIRECTORY_SEPARATOR; //1
$storeFolder = '../../../resources/uploads';
if (!empty($_FILES)) {
$tempFile = $_FILES['uploadedfile']['tmp_name']; //3
$extension = pathinfo($_FILES['uploadedfile']['name'], PATHINFO_EXTENSION);
$attachment_hash = md5($tempFile);
$new = $attachment_hash.'.'.$extension;
// complete creating attachment object with newly created attachment_hash
$attachment->hash = $new;
$attachment->save();
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds; //4
$targetFile = $targetPath. $new; //5
move_uploaded_file($tempFile,$targetFile); //6
chmod($targetFile, 0777);
}
else
{
return "error";
}
Service Provider (I thought publishing the uploads folder might work - nope.)
public function boot()
{
require __DIR__ . '/Http/routes.php';
$this->loadViewsFrom(__DIR__ . '/resources/views', 'ariel');
$this->publishes([
__DIR__ . '/resources/uploads' => public_path('vendor/uploads'),
], 'public');
$this->publishes([
__DIR__ . '/../database/migrations' => database_path('migrations')], 'migrations');
}
HERE WE GO. I used the (well-documented) the Storage facade to work with the local filesystem (project).
https://laravel.com/docs/5.1/filesystem
$attachment->spot_buy_item_id = $id;
$attachment->name = $_FILES['uploadedfile']['name'];
$attachment->created_ts = Carbon::now();
$ds = DIRECTORY_SEPARATOR; //1
$storeFolder = 'uploads';
if (!empty($_FILES)) {
$tempFile = $_FILES['uploadedfile']['tmp_name']; //3
$extension = pathinfo($_FILES['uploadedfile']['name'], PATHINFO_EXTENSION);
$attachment_hash = md5($tempFile);
$new = $attachment_hash.'.'.$extension;
// complete creating attachment object with newly created attachment_hash
$attachment->hash = $new;
$attachment->save();
$tmpPath = $storeFolder . $ds;
$targetFile = $tmpPath . $new; //5
Storage::disk('local')->put($targetFile, file_get_contents($request->file('uploadedfile')));
}
else
{
return "error";
}

Categories