I want to upload file with yii, I kinda did it. When I hit the submit button the file is saved in the folder where it should be. However, I want to add the filename to the database as well. How can I achieve this?
this is my controller :
public function actionUpload()
{
$model = new TourImage();
if (Yii::$app->request->isPost) {
$model->imageFile = UploadedFile::getInstance($model, ‘imageFile’);
if ($model->upload()) {
// file is uploaded successfully
return;
}
}
return $this->render(‘upload’, [
‘model’ => $model
]);
}
You can extract the name of the original file from UploadedFile.getInstance() and assign it to the attribute of your model (This is normally done in your model "TourImage", in the upload method that you have had to implement).
Therefore if you have this in your controller action:
$model->imageFile = UploadedFile::getInstance($model, 'imageFile');
Then, in the upload() method of your TourImage model:
$this->your_model_attribute = $this->imageFile->name; // The original name of the file being uploaded
Change your_model_attributes to the attribute of your model where you want to save the file name.
Look at the public properties of the UploadedFile object:
https://www.yiiframework.com/doc/api/2.0/yii-web-uploadedfile
Related
I have created the following 4 model and its table structure for my project:
Media.php To upload images in app
Medias table structure
id | path
Example of path:uploads/images/media/food-1542110154.jpg
Post.php Create post
Posts table structure
id | title | content
FeaturedImage.php Featured image for post
Posts table structure
id | post_id| path
Post model and FeaturedImage model are in a one-to-one relationship
UploadImage.php To resize the uploaded image and move it to another directory. This model doesn't have migration and controller
Code snippet from PostsController.php to create the post
use App\UploadImage;
use App\Media;
class PostController extends Controller
{
private $imagePath= "uploads/images/post/";
public function store(Request $request)
{
$post = new Post;
$post->title = $request->title;
$post->content = $request->content;
$post->save();
$media = Media::find($request->featured);
if (!File::exists($this->imagePath)) {
File::makeDirectory($this->imagePath);
}
$upload = new UploadImage;
$image= $upload->uploadSingle($this->banner, $media->path, 400,300);
$post->image()->save(new FeaturedImage([
'path' => $image
]));
}
Session::flash('success', 'Post created sucessfully !');
return redirect()->route('post.index');
}
Code snippet from UploadImage.php
use Intervention\Image\Facades\Image;
use Spatie\LaravelImageOptimizer\Facades\ImageOptimizer;
use Illuminate\Database\Eloquent\Model;
class UploadImage extends Model
{
public function uploadSingle($savePath, $image,$width,$height)
{
Image::make(public_path($image))->fit($width, $height)->save($savePath);
ImageOptimizer::optimize($savePath);
return $savePath;
}
}
In my Laravel app, I'm trying to edit dimension of the already uploaded image with method written in UploadImage.php and save edited image in post directory and save its path in featured_images table.
But I've been getting **Can't to write image data to path ** error.
I would be very thankful if anyone could point out the mistakes that I've made.
Please do not mark this as duplicate content. As I've been gone through almost all posts related to this kind of error and they have been no help to me.
Tweaked few lines in my UploadImage.php model and got it solved.
public function uploadSingle($savePath, $image,$width,$height)
{
$filename = basename($image);
$location = $savePath . $filename;
Image::make($image)->save($location);
ImageOptimizer::optimize($location);
return $location;
}
The upload script is working, the file also gets saved by the correct/desired name. However, while storing data in database, it stores .tmp filename instead
controller code:
public function store(CreateChapterRequest $request)
{
if($request['chapter_content_type']==6) {
//upload file
$record_save = $this->processFile($request->file('chapter_document'));
$request['chapter_document']=$record_save;
}
Chapter::create($request->all());
}
protected function processFile($requestData)
{
$input['chapter_document'] = time().'.'.$requestData->getClientOriginalExtension();
$destinationPath = public_path('uploads/chapters/');
$requestData->move($destinationPath, $input['chapter_document']);
return $input['chapter_document'];
}
It's storing file name as C:\project\xampp\tmp\phpD837.tmp. What's wrong?
It works with $record=new Chapter(); $record->save($request->all()); but not with ::create()
Don't know why!
i want to create form with php that have multiple part and type of data. Such as:
Input Text (name,title, description,etc)
Input image (header_img)
Input Multiple image (slider)
The point is i want to create a lot of data include upload file in one page using php.
In post method, i try standard logic, upload one by one of image with if else logic, with a lot of if else logic and different name and insert it in each field of database (one field in one field database) huft....
if($_FILES['imghead']['size']!=0){
// run upload method
}
And for edit , i try it manually, same as post method, using if else for each field. for example:
if($_FILES['imghead']['size']!=0){
// run upload method
}
if($_FILES['slider1']['size']!=0){
// run upload method
}
if($_FILES['slider2']['size']!=0){
// run upload method
}
if($_FILES['slider3']['size']!=0){
// run upload method
}
// etc
But the problem is, i think my method is not really good, its not effective and i must write a lot of code and check them one bu one with if else logic.
My Question:
Do you know how to optimize my logic to real simple code? specially CRUD.
i have try grocery crud but i need more feature like multiple images upload
There is a way to implement multiple images upload with grocerycrud, in the controller you need to asign a different name method to every upload field that you need and then just copy paste the main method in the Grocery_CRUD.php file and change the name to the same that you assigned
Controller code:
$crud->set_field_upload('file1','assets/uploads');
$crud->set_another_field_upload('file2','assets/uploads');
This is the code that you need to copy, (route:htdocs\app_name\application\libraries\Grocery_CRUD.php)
public function set_field_upload($field_name, $upload_dir = '')
{
$upload_dir = !empty($upload_dir) && substr($upload_dir,-1,1) == '/'
? substr($upload_dir,0,-1)
: $upload_dir;
$upload_dir = !empty($upload_dir) ? $upload_dir : 'assets/uploads/files';
/** Check if the upload Url folder exists. If not then throw an exception **/
if (!is_dir(FCPATH.$upload_dir)) {
throw new Exception("It seems that the folder \"".FCPATH.$upload_dir."\" for the field name
\"".$field_name."\" doesn't exists. Please create the folder and try again.");
}
$this->upload_fields[$field_name] = (object) array(
'field_name' => $field_name,
'upload_path' => $upload_dir,
'encrypted_field_name' => $this->_unique_field_name($field_name));
return $this;
}
Just paste it below and change the function name with the same name assigned in your controller:
public function set_another_field_upload($field_name, $upload_dir = '')
{
$upload_dir = !empty($upload_dir) && substr($upload_dir,-1,1) == '/'
? substr($upload_dir,0,-1)
: $upload_dir;
$upload_dir = !empty($upload_dir) ? $upload_dir : 'assets/uploads/files';
/** Check if the upload Url folder exists. If not then throw an exception **/
if (!is_dir(FCPATH.$upload_dir)) {
throw new Exception("It seems that the folder \"".FCPATH.$upload_dir."\" for the field name
\"".$field_name."\" doesn't exists. Please create the folder and try again.");
}
$this->upload_fields[$field_name] = (object) array(
'field_name' => $field_name,
'upload_path' => $upload_dir,
'encrypted_field_name' => $this->_unique_field_name($field_name));
return $this;
}
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).
I would like to create a controller that handles uploading files to user specific folders. I currently have a from that allows users to upload a file which sends the post data to the controller.
What I would like the controller to do is take the uploaded file, and place it in a folder e.g. /public/{username}/files
But I am not too sure how to approach it using symfony.
As Mahok commented, the Symfony2 docs are useful here.
I would follow them with the added additions. When you save the document, pass the username:
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
//get the user and pass the username to the upload method
$user = $this->get('security.context')->getToken()->getUser();
$document->upload($user->getUsername());
$em->persist($document);
$em->flush();
$this->redirect(...);
}
When you upload the file, use the username:
public function upload($username)
{
if (null === $this->file) {
return;
}
//use the username for the route
$this->file->move(
"/public/$username/files/",
$this->file->getClientOriginalName()
);
// set the path property to the filename where you've saved the file
$this->path = $this->file->getClientOriginalName();
// clean up the file property as you won't need it anymore
$this->file = null;
}
Saving it this way you wont actually need to use the extra entity methods like "getAbsolutePath" etc
Note that you may have to slugify the username if you accept spaces etc.
Edit:
You will need to set up a oneToMany relationship for users to files so that you can locate the file later on.
This might help you---
$upload_dir = "your upload directory/{username}";
if (!is_dir($upload_dir)) {
#mkdir($upload_dir, "755", true);
}
move_uploaded_file($source,$destination);