I have a photo upload form which goes to this code
$this->validate($request, [
'image' => 'required|image|max:3000|mimes:jpeg,jpg,png',
]);
$user = Auth::user();
$usersname = $user->username;
$file = $request->file('image');
$ext = $file->getClientOriginalExtension();
$path = Storage::disk('uploads');
$filename = $usersname . '.' . $ext;
if (Storage::disk('uploads')->has($filename)) {
Storage::delete($filename);
}
Storage::disk('uploads')->put($filename, File::get($file));
$resizedImg = Image::make($path . DIRECTORY_SEPARATOR . $filename)->resize(200,200)->save($path . DIRECTORY_SEPARATOR . $filename);
return redirect()->route('profile.index',
['username' => Auth::user()->username]);
}
When I make this code execute it gives me this error
ErrorException in ProfileController.php line 71:
Object of class Illuminate\Filesystem\FilesystemAdapter could not be converted to string
line 71 is the line beginning with $resizedImg but the photo does save to the correct directory just not resized.
I defined uploads in the filesystems.php file as following
'disks' => [
'uploads' => [
'driver' => 'local',
'root' => public_path('/uploads'),
],
$path contents driver in it, but you're trying to use it as string, that's the problem. Try to use something like:
$path = '/uploads';
Related
Help :(, I'm a newbie trying out CKeditor 5 for my post form
I'm using ckeditor 5, and i'm trying to upload images in it. But, when i'm trying to load image i have a massage: Cannot upload file filename.
Where's the problem?
Init function :
ClassicEditor
.create( document.querySelector( '#body' ), {
ckfinder:{
uploadUrl: "{{ route('ckeditor.upload') .'?token=' . csrf_token()}}"
}
} )
.catch( error => {
console.error( error );
} );
PHP config :
$config['backends']['default'] = array(
'name' => 'default',
'adapter' => 'local',
'baseUrl' => config('app.url').'/userfiles/',
'root' => public_path('/userfiles/'),
'chmodFiles' => 0777,
'chmodFolders' => 0755,
'filesystemEncoding' => 'UTF-8'
);
Controller :
public function uploadImage(Request $request){
if($request -> hasFile('upload')){
$originame = $request->file('upload')->getClientOriginalName();
$fileName = pathinfo($originame, PATHINFO_FILENAME);
$extension = $request->file('upload')->getClientOriginalExtension();
$fileName = $fileName . '_' . time() . '.' . $extension;
$request->file('upload')->move(public_path('media'), $fileName);
$url = asset('media/' . $fileName);
return response()->json(['fileName' => $fileName, 'uploaded'=> 1, 'url' => $url]);
}
}
Thank you, help me :')
Case: Uploading avatars. This is working offline on my localhost, but after putting it online to 000webhost hosting provider, this does not work anymore. The file is NOT being uploaded but Laravel does not returns any error. Any idea to solve this?Thankyou.
This is my controller:
if ($request->hasFile('avatar'))
{
$user = User::find(Auth::user()->id);
$avatar = $request->file('avatar'); // in here
$filename = time() . '.' . $avatar->getClientOriginalName();
$path = base_path();
$path = str_replace("gsm-cp","public_html",$path);
$destinationPath = $path.'/img/avatars';
$avatar->move($destinationPath, $filename);
$user->avatar = $filename;
$user->save();
}
This is my config/filesystems.php
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
],
...
You can simplify your code by using storeAs(), as well as replacing $user = User::find(Auth::user()->id); with $user = Auth::user();.
storeAs() takes a path, the filename to store, and takes an optional array, which can for example specify the disk -- here, we're using the public one. This would store the images in ./storage/app/public/avatars/1597750757_1.jpg for user with ID 1.
if ($request->hasFile('avatar'))
{
$user = Auth::user();
$avatar = $request->file('avatar');
$filename = time().'_'.$user->id.'.'.$file->getClientOriginalExtension();
$path = $avatar->storeAs("/avatars/", $filename, ['disk' => 'public']);
$user->avatar = $filename;
$user->save();
}
You may alternatively want to store down the path, and not just the filename. The storeAs() method returns the full path to the image (including its name).
File Storage docs
My goal is to upload a large file to dropbox and because the waiting time can be too long I want to split the process and upload the file through a queue.
I'm doing the following:
I upload a file (that can be large)
I save it on local storage
I save data about the file in database.
In a queue I want to get the file and move it to a dropbox disk.
The problem is that when I do the last step I get the following error
ErrorException
fopen(files/7u7v6LYq72vmXLqeWPsc6b0khiy9pEbFicVJuK2W.pdf): failed to open stream: No such file or directory
I tried different approaches but I can't find a solution.
My code
Controller method:
public function uploadToDropbox(Request $request){
$data = $request->validate([
'file' => 'required|mimes:jpeg,jpg,png,doc,docx,pdf,txt,mp3,mp4,avi|max:600000',
'first_name' => 'required',
'last_name' => 'required',
]);
/** #var \Symfony\Component\HttpFoundation\File\File $uploadedFile */
$uploadedFile = $data['file'];
$path = Storage::disk('local')->putFileAs( 'file', $uploadedFile, $uploadedFile->getClientOriginalName());
$file = new File();
$file->first_name = $data['first_name'];
$file->last_name = $data['last_name'];
$file->file = $path;
$file->original_name = $uploadedFile->getClientOriginalName();
$file->size = $uploadedFile->getSize();
$file->real_path = $uploadedFile->getRealPath();
$file->save();
$result = ProcessFile::dispatch($file);
if($result){
return Redirect::back()->withErrors(['msg'=>'Successfully file uploaded']);
} else {
return Redirect::back()->withErrors(['msg'=>'File failed to upload']);
}
}
Queue job:
public function handle()
{
if (Storage::disk('local')->exists($this->file->file)) {
$name = strtolower($this->file->first_name) . '_' . strtolower($this->file->last_name);
$rez = Storage::disk('dropbox')->putFileAs(
'challenge-files/' . $name . '/',
$this->file->file,
$this->file->original_name
);
Log::info('message: ' . $rez);
} else {
Log::alert('falseeeee');
}
}
FilesystemAdapter puthFileAs method:
public function putFileAs($path, $file, $name, $options = [])
{
$stream = fopen(is_string($file) ? $file : $file->getRealPath(), 'r');
// Next, we will format the path of the file and store the file using a stream since
// they provide better performance than alternatives. Once we write the file this
// stream will get closed automatically by us so the developer doesn't have to.
$result = $this->put(
$path = trim($path.'/'.$name, '/'), $stream, $options
);
if (is_resource($stream)) {
fclose($stream);
}
return $result ? $path : false;
}
filesystems.php local disk configs
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
'permissions' => [
'file' => [
'public' => 0664,
'private' => 0600,
],
'dir' => [
'public' => 0775,
'private' => 0700,
],
],
],
Probably, you haven't modify the permissions mappings in your filesystems configuration file.
Look for the
dir
array and check if the
public
number is
0775
if it is not, change it to that number
Look for
file
change 'public' => 0664
I am working on a project, now i need to rename a key using its prefix in s3 php sdk api. i couldn't find it, if any can help. Thanks
function moveFile($oldPath,$newPath){
$oKey = $this->getKey($oldPath);
$nKey = $this->getKey($newPath);
try{
// Copy an object.
$this->o->copyObject(array(
'Bucket' => $this->bucket,
'ACL' => 'public-read',
'Key' => $nKey,
'CopySource' => "{$this->bucket}/{$oKey}"
));
$this->deleteFile($oldPath);
} catch (S3Exception $e) {
echo $e->getMessage() . "\n";
return false;
}
}
You can rename s3 files using below code :
$s3sdk = new Sdk($awsConfig);
$s3 = $s3sdk->createS3();
$s3->registerStreamWrapper();
rename($oldName, $newName);
both names need to contain the full s3 path e.g:
"s3://yourBucketName/path/to/file"
Basically registerStreamWrapper() enables PHP filesystem commands for s3 files.
I did this, you guys answered late. i did it myself but LuFFy answer is also correct.
function renameFolder($oldPath,$newPath){
$oKey = $this->getKey($oldPath);
if(strpos($oKey,'/')==false){$oKey.='/';}
//echo '<br>oKey: '.$oKey.'<br>';
try{
// Copy an object.
/*$this->o->copyObject(array(
'Bucket' => $this->bucket,
'ACL' => 'public-read',
'Key' => $nKey,
'CopySource' => "{$this->bucket}/{$oKey}"
));*/
$result = $this->o->listObjects([
'Bucket' => $this->bucket, // REQUIRED
'Prefix' => $oKey,
]);
foreach($result['Contents'] as $file){
//echo '<br>objectKey: '.$file['Key'].'<br>';
$nKey = str_replace($this->getLastKey($oldPath),$this->getLastKey($newPath),$file['Key']);
//echo '<br>nKey: '.$nKey.'<br>';
$this->o->copyObject(array(
'Bucket' => $this->bucket,
'ACL' => 'public-read',
'Key' => $nKey,
'CopySource' => "{$this->bucket}/".$file['Key'].""
));
}
$this->deleteDir($oldPath);
}catch(S3Exception $e) {
echo $e->getMessage() . "\n";
return false;
}
}
I have managed to rename existing files on the batch using below steps:
Lets say your config/filesystems.php looks like this:
'disks' => [
's3_test_bucket' => [
'driver' => 's3',
'key' => env('AWS_KEY', 'your_aws_key_here'),
'secret' => env('AWS_SECRET','your_aws_secret_here'),
'region' => env('AWS_REGION', 'your_aws_region_here'),
'version' => 'latest',
'bucket' => 'my-test-bucket',
],
];
Let's say, you have my-test-bucket on your AWS S3.
Lets say you have following files inside the my-test-bucket/test-directory directory.
i.e.
test-files-1.csv
test-files-2.csv
test-files-3.csv
Call below function to rename existing files on a selected directory on S3 Bucket.
$directoryPath = 'test-directory';
$storage = new MyStorageRepository();
$storage->renameAnyExistingFilesOnImportDirectory('my-test-bucket', 'test-directory');
Output: files should be rename as below on my-test-bucket/test-directory directory:
test-files-1--1548870936.csv
test-files-2--1548870936.csv
test-files-3--1548870936.csv
Include the below library class or methods on your class and you should be good.
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Storage;
class MyStorageRepository
{
public function renameAnyExistingFilesOnImportDirectory($bucket, $directoryPath)
{
$directoryPath = App::environment() . '/' . $directoryPath;
$storage = Storage::disk('s3_test_bucket');
$suffix = '--' . time(); // File suffix to rename.
if ($storage->exists($directoryPath)) {
$this->renameStorageDirectoryFiles($directoryPath, $storage, $suffix);
}
}
private function getNewFilename($filename, $suffix = null)
{
$file = (object) pathinfo($filename);
if (!$suffix) {
$suffix = '--' . time();
}
return $file->dirname . '/' . $file->filename . $suffix . '.' . $file->extension;
}
private function renameStorageDirectoryFiles($directoryPath, $storage = null, $suffix = null, $filesystemDriver = null)
{
if (!$storage) {
$storage = Storage::disk($filesystemDriver);
}
// List all the existing files from the directory
$files = $storage->files($directoryPath);
if (count($files) < 1 ) return false;
foreach($files as $file) {
// Get new filename
$newFilename = Helpers::getNewFilename($file, $suffix);
// Renamed the files
$storage->move($file, $newFilename);
}
}
}
Edit: It turns out this issue happens while trying to upload .sql files. It's not the file name.
When I try to upload a file with this name: forge_2016-02-08_--USERS THOUGH.sql I'm shown this error below:
ErrorException in FileinfoMimeTypeGuesser.php line 69:
Array to string conversion
and
at HandleExceptions->handleError('8', 'Array to string conversion', '/home/forge/example.com/vendor/symfony/http-foundation/File/MimeType/FileinfoMimeTypeGuesser.php', '69', array('path' => '/tmp/phppkDGK8', 'finfo' => object(finfo)))
at finfo->file('/tmp/phppkDGK8') in FileinfoMimeTypeGuesser.php line 69
at finfo->file('/tmp/phppkDGK8') in FileinfoMimeTypeGuesser.php line 69
at FileinfoMimeTypeGuesser->guess('/tmp/phppkDGK8') in MimeTypeGuesser.php line 139
I have no idea why this error is happening. Here's my upload code:
$baseDir = storage_path('uploads');
$file = $request->file('file');
$mimeType = $file->getMimeType();
$name = str_random(6) . time() . '-' . str_replace(' ', '_', Str::ascii($file->getClientOriginalName()));
$file->move($baseDir, $name);
$path = $baseDir . '/' . $name;
$data = ['path' => $path, 'ip' => userIP(), 'name' => $file->getClientOriginalName(), 'mime' => $mimeType, 'size' => $file->getClientSize()];
$status = Uploads::create($data);
if ($status) {
$su = true;
Please help guys. I don't know why this is happening.
I fixed it by changing
$mimeType = $file->getMimeType();
to
$mimeType = $file->getClientMimeType();
This fixed it.