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 :')
Related
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
Here below is the kartik file input widget in update_form.
echo FileInput::widget(
[
'name' => 'BriefRequirements[requirement_value][]',
'attribute' => 'assets_file',
'id' => 'assets_file',
'options' => ['multiple' => true],
'pluginOptions' => [
'overwriteInitial' => false,
'initialPreview' => $image_url,
'deleteUrl' => ' site/delete',
'initialPreviewAsData' => true,
'initialPreviewFileType' => 'image' //'pdf'
]
]
);
below is multiple image loading code,
foreach ($modelRequirements as $req) {
$image_url[] = Yii::$app->request->baseUrl
. '/theme/business_campaign_files/'
. $req['requirement_value'];
}
I need help with my two questions:
Need to show all selected format files like image, pdf, doc etc [I tried to like 'initialPreviewFileType'=>'any'] not working.
I want to pass the selected image id to action to delete the image? - 'deleteUrl' => ' site/delete','id'=>12, <-- like this.
In the below code i got the result for my two questions.
$initializeConfig = [];
$initializeConfig1 = [];
if ($modelRequirements) {
foreach ($modelRequirements as $req) {
$extension = substr(
$req['requirement_value'],
strrpos($req['requirement_value'], '.') + 1
);
$image_url[] = Yii::$app->request->baseUrl
. '/theme/business_campaign_files/'
. $req['requirement_value'];
$initializeConfig1['url'] = Url::toRoute('delete-requirement');
$initializeConfig1['key'] = $req['id'];
$initializeConfig1['type'] = $type;
array_push($initializeConfig, $initializeConfig1);
}
}
In the above code i got the result for my two questions.
For delete -> mentioned url I wrote the delete function, also through key parameter I passed the id.
For view all the extension files u have to send like "type" $initializeConfig1['type'] = $type; in the type variable i am getting the image extension based on the extension i am setting the format of the file like[pdf,xlsx,image].
easyOne
Various methods to manage your preview. The following features are demonstrated in this example:
For Single Image you can make it Multiple Same as
$files = array();
$files['initialPreview'] = Url::base(TRUE) . '/' . $uploadurl . $newFileName;
$files['initialPreviewAsData'] = true;
//FOR PDF
if ($fieldtype == 'pdf') {
$files['initialPreviewConfig'][] = array('type' => 'pdf', 'key' => $newFileName);
} else {
//FOR IMAGES
$files['initialPreviewConfig']['key'] = $newFileName;
}
$files['namefile'] = $newFileName;
JSON Response :
{
"initialPreview": "http://localhost/yii2/uploads/project/brochure/fileone.pdf",
"initialPreviewAsData": true,
"initialPreviewConfig": [
{
"type": "pdf",
"key": "fileone.pdf"
}
],
"namefile": "fileone.pdf"
}
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';
I successfully saved the path of photo into mysql database.My question is,how to render correctly in templates?I tried
<td width="129" rowspan="5"><img src= "/uploads/photos<?php echo $applicant->photo?>"width="129" height="129"/></td>
Not working.
In my action, i tried
$photo = $this->form->getValue('photo');
$filename = 'photo'.sha1($photo->getOriginalName());
$extension = $photo->getExtension($photo->getOriginalExtension());
//$photo->save(sfConfig::get('sf_upload_dir').'/' . $filename . $extension);
$photo->save(sfConfig::get('sf_upload_dir') . '/'.$photo) . date('Ym') . '/' . $filename . $extension);
and in my form i tried
$this->widgetSchema['photo'] = new sfWidgetFormInputFileEditable(array(
'label' => 'Photo',
'file_src' => '/uploads/photos/'.$this->getObject()->getPhoto(),
'is_image' => true,
'edit_mode' => !$this->isNew(),
'template' => '<div class="sublabel">%file%<br />%input%<br />%delete% %delete_label%</div>',
));
$this->validatorSchema['photo'] = new sfValidatorFile(array(
'required' => false,
'path' => sfConfig::get('sf_upload_dir').'/photos',
'mime_types' => 'web_images',
));
I refer to http://samsonasik.wordpress.com/2012/08/31/zend-framework-2-creating-upload-form-file-validation/ and follow this, I can upload 1 file successfully by using rename filter in ZF2.
However when I use this way to upload 2 files, it goes wrong. I paste my code as following:
$this->add(array(
'name' => 'bigpicture',
'attributes' => array(
'type' => 'file'
),
'options' => array(
'label' => 'Big Pic'
)
));
$this->add(array(
'name' => 'smallpicture',
'attributes' => array(
'type' => 'file'
),
'options' => array(
'label' => 'Small Pic'
)
));
<div class="row"><?php echo $this->formRow($form->get('smallpicture')) ?></div>
<div class="row"><?php echo $this->formRow($form->get('bigpicture')) ?></div>
$data = array_merge(
$request->getPost()->toArray(),
$request->getFiles()->toArray()
);
$form->setData($data);
if ($form->isValid()) {
$product->exchangeArray($form->getData());
$picid = $this->getProductTable()->saveProduct($product);
$pathstr = $this->md5path($picid);
$this->folder('public/images/product/'.$pathstr);
//move_uploaded_file($data['smallpicture']['tmp_name'], 'public/images/product/'.$pathstr.'/'.$picid.'_small.jpg');
//move_uploaded_file($data['bigpicture']['tmp_name'], 'public/images/product/'.$pathstr.'/'.$picid.'_big.jpg');
$fileadaptersmall = new \Zend\File\Transfer\Adapter\Http();
$fileadaptersmall->addFilter('File\Rename',array(
'source' => $data['smallpicture']['tmp_name'],
'target' => 'public/images/product/'.$pathstr.'/'.$picid.'_small.jpg',
'overwrite' => true
));
$fileadaptersmall->receive();
$fileadapterbig = new \Zend\File\Transfer\Adapter\Http();
$fileadapterbig->addFilter('File\Rename',array(
'source' => $data['bigpicture']['tmp_name'],
'target' => 'public/images/product/'.$pathstr.'/'.$picid.'_big.jpg',
'overwrite' => true
));
$fileadapterbig->receive();
}
the above are form,view,action.
using this way, only the small picture uploaed successfully. the big picture goes wrong.
a warning flashed like the following:
Warning:move_uploaded_file(C:\WINDOWS\TMP\small.jpg):failed to open stream:Invalid argument in
E:\myproject\vendor\zendframework\zendframework\library\zend\file\transfer\adapter\http.php
on line 173
Warning:move_uploaded_file():Unable to move 'C:\WINDOWS\TMP\php76.tmp'
to 'C:\WINDOWS\TEMP\big.jpg' in
E:\myproject\vendor\zendframework\zendframework\library\zend\file\transfer\adapter\http.php
on line 173
Who can tell me how to upload more than 1 file in this way. you know, the rename filter way similar to above. thanks.
I ran into the same problem with a site i did. The solution was to do the renaming in the controller itself by getting all the images and then stepping through them.
if ($file->isUploaded()) {
$pInfo = pathinfo($file->getFileName());
$time = uniqid();
$newName = $pName . '-' . $type . '-' . $time . '.' . $pInfo['extension'];
$file->addFilter('Rename', array('target' => $newName));
$file->receive();
}
Hope this helps point you in the right direction.
I encountered the same problem and i managed to make it work using the below code;
$folder = 'YOUR DIR';
$adapter = new \Zend\File\Transfer\Adapter\Http();
$adapter->setDestination($folder);
foreach ($adapter->getFileInfo() as $info) {
$originalFileName = $info['name'];
if ($adapter->receive($originalFileName)) {
$newFilePath = $folder . '/' . $newFileName;
$adapter->addFilter('Rename', array('target' => $newFilePath,
'overwrite' => true));
}
}