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/
Related
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;
});
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, '.'));
public function upload(Request $request){
$user = User::findOrFail(auth()->user()->id);
$filename = time() . '.jpg';
$filepath = public_path('uploads/');
move_uploaded_file($_FILES['filename']['tmp_name'], $filepath.$filename);
move_uploaded_file($_FILES['filename']['tmp_name'], public_path('uploads/newfolder').$filename);
echo $filepath.$filename;
}
How can I upload the same image into different folders.
I have tried the above code and it doesn't work in the other folder.
You can't run move_uploaded_file twice for the same file because as it name says, it moves the file, so on the second run, the original file won't exist anymore.
You must copy the file:
public function upload(Request $request){
$user = User::findOrFail(auth()->user()->id);
$filename = time() . '.jpg';
$filepath = public_path('uploads/');
move_uploaded_file($_FILES['filename']['tmp_name'], $filepath.$filename);
// Note that here, we are copying the destination of your moved file.
// If you try with the origin file, it won't work for the same reason.
copy($filepath.$filename, public_path('uploads/newfolder').$filename);
echo $filepath.$filename;
}
use Illuminate\Support\Facades\Storage;
public function upload(Request $request){
$filename = time() . '.jpg';
$filepath = public_path('uploads/newfolder/');
$file = $request->file( "filename" );
Storage::putFileAs( $filepath, $file, $filename );
echo Storage::url( 'uploads/newfolder/'.$filename );
}
You should try this:
Try with copy upload folder image to new folder like:
use Illuminate\Support\Facades\File;
$imgUpload = File::copy(public_path().'/uploads/'. $filename, public_path().'/newfolder/'. $filename);
I'm working with laravel 5.4 I have a form which I can upload my logoimage and in update function I have this code:
//Save logo
if ($request->hasFile('logo')) {
$avatar = $request->file('logo');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
$location = public_path('avatars/logos/');
$request->file('logo')->move($location, $filename);
$oldFilename = $general_Settings->logo;
$general_Settings->logo = $filename;
Storage::delete($oldFilename);
}
$general_Settings->save();
for updating my image which is work but as you see I have Storage::delete($oldFilename); this part doesn't work and just keep the old image.
what do you think is issue of that?
Solved:
The issue was Filesystem.php I made my local root set to 'root' => public_path('avatars/'), and changed all my functions in my app because no way to save images in sub-folders and delete them just can save in sub-folders.
then my update function become like this:
if ($request->hasFile('logo')) {
$avatar = $request->file('logo');
$filename = 'sitelogo' . '-' . time() . '.' . $avatar->getClientOriginalExtension();
$location = public_path('avatars/');
$request->file('logo')->move($location, $filename);
$general_Settings->logo = $filename;
}
$general_Settings->save();
I hope this help someone.
Since, You have stored logo file name only not full path of file,
You need to give full path from public folder to delete image. Change delete line as:
if ($request->hasFile('logo')) {
$avatar = $request->file('logo');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
$location = public_path('avatars/logos/');
$request->file('logo')->move($location, $filename);
$oldFilename = $general_Settings->logo;
$file_path = "avatars/logos/".$oldFilename;
$general_Settings->logo = $filename;
Storage::delete($file_path);
}
$general_Settings->save();
This might work.
I am using PHP (Symfony2) in my project which has image upload feature. Inside controller:
if ($request->isXmlHttpRequest() && $request->isMethod('POST')) {
$index=(int)$request->request->get('index');
$image_file = $request->files->get('shop_bundle_managementbundle_posttype')['images'][$index]['file'];
$image= new Image();
$image->setFile($image_file);
$image->setSubDir('hg');
$image->upload();
$em->persist($image);
$em->flush();
}
I use a class UploadFileMover that handle the file upload. I didn't write the following code but as I understand, an MD5 hash will be created from the original file name and used as filename. But the instance of UploadedFile contains a file name like "PHP"+number.tmp, not the original as stored in computer filesystem.
class UploadFileMover {
public function moveUploadedFile(UploadedFile $file, $uploadBasePath,$relativePath)
{
$originalName = $file->getFilename();
$targetFileName = $relativePath . DIRECTORY_SEPARATOR . $originalName;
$targetFilePath = $uploadBasePath . DIRECTORY_SEPARATOR . $targetFileName;
$ext = $file->getExtension();
$i=1;
while (file_exists($targetFilePath) && md5_file($file->getPath()) != md5_file($targetFilePath)) {
if ($ext) {
$prev = $i == 1 ? "" : $i;
$targetFilePath = $targetFilePath . str_replace($prev . $ext, $i++ . $ext, $targetFilePath);
} else {
$targetFilePath = $targetFilePath . $i++;
}
}
$targetDir = $uploadBasePath . DIRECTORY_SEPARATOR . $relativePath;
if (!is_dir($targetDir)) {
$ret = mkdir($targetDir, umask(), true);
if (!$ret) {
throw new \RuntimeException("Could not create target directory to move temporary file into.");
}
}
$file->move($targetDir, basename($targetFilePath));
return str_replace($uploadBasePath . DIRECTORY_SEPARATOR, "", $targetFilePath);
}
}
This class is instanciated when an image is uploaded. In other words, I have an Entity Image that has a method upload. Inside entity class:
public function upload()
{
if (null === $this->getFile()) {
return;
}
$uploadFileMover = new UploadFileMover();
$this->path = $uploadFileMover->moveUploadedFile($this->file, self::getUploadDir(),$this->subDir);
$this->file = null;
}
I var_dumped the filename all across the different steps but I cannot figure out where it is transformed to PHP16653.tmp.
Can it be related to an APACHE related configuration? Your help is appreciated. I really did a lot of research for similar issue in the web to no avail.
The problem was created by the line:
$originalName = $file->getFilename();
Use:
$originalName = $file->getClientOriginalName();
instead.