upload file to sql table using a path - php

I'm trying to upload a file to a MySQL table using a path (the file will be save on the server asd in the table a link for him). Here is what I've done:
My view is:
<div class="row">
<?php echo $form->labelEx($model,'doc_ordered_recieved'); ?>
<?php echo $form->fileField($model,'doc_ordered_recieved'); ?>
<?php echo $form->error($model,'doc_ordered_recieved'); ?>
</div>
My model is:
array('doc_ordered_recieved','file','types'=>'pdf', 'allowEmpty'=>true, 'on'=>'insert,update'),
and my controller is:
public function actionCreate()
{
$model=new Orders;
if(isset($_POST['Orders']))
{
$model->attributes=$_POST['Orders'];
$uploadedFile = CUploadedFile::getInstance($model,'doc_ordered_recieved');
if($model->save())
{
if(!empty($uploadedFile)) // check if uploaded file is set or not
{
if($model->doc_ordered_recieved== null || empty($model->doc_ordered_recieved)){
$rnd = rand(0,9999);// generate random number between 0-9999
$fileName = "{$rnd}-{$uploadedFile}";
$model->doc_ordered_recieved= $fileName;
}
$uploadedFile->saveAs(dirname(__FILE__)..'/files/'. $model->doc_ordered_recieved);
// redirect to success page
}
$this->redirect(array('view','id'=>$model->oid));
}
}
$this->render('create',array('model'=>$model,
));
}
The table is defined as varchar is that ok????
The file should be saved in d:\xampp\htdocs\filse
Please help me it always says: doc_ordered_recieved can't be blank

Related

How to store file images into mysql (Codeigniter)

I tried to upload file images into mysql using Codeigniter
This is likely my upload view:
<label>Upload File</label>
<input type="file" class="form-control" name="images">
</div>
I've done with image name, description, etc.
I tried to save it into database, just like normal input form.
The result, column "images" cannot be null. I have set column "images" with varbinary(3000)
Am I doing it wrong?
EDITED:
My Controller:
public function save(){
$this->gallery_model->save_foto();
$this->session->set_flashdata('msg','FOTO BERHASIL DI UPLOAD');
redirect(base_url('gallery'));
}
My Model
<?php
class Gallery_model extends CI_Model {
public function __construct() {
parent::__construct();
}
public function save_foto(){
$data['id'] = date('U');
$data['nm_foto'] = $this->input->post('nm_foto');
$data['username'] = $this->input->post('username');
$data['tanggal'] = date('j F Y');
$data['images'] = $this->input->post('images');
$data['deskripsi'] = $this->input->post('deskripsi');
$this->db->insert( 'gallery', $data );
}
}
You can't directly upload image into database , Insert image path
For upload image form form add
enctype="multipart/form-data"
in form .
For more help regarding image upload in codeigniter
Codeigniter Image Upload
You can store images but its not advisable.
The "correct" way to do it is to store the files somewhere on your server and store the URI in the database.
The problem is that images can be quite large, this can result in a big load on your database which is unnecessary. When you work on a larger scale project you may have multiple database that need to be synchronised, when you database is larger then it need to be you unnecessary slow down your network.
If you still want the image stored in the datebase, you can store it as an BLOB type. See the MySQL documenation
You can insert it then with the following example code
$data['image'] = file_get_contents($_FILES['image']['tmp_name']);
If someone met an error and getting tired just like me, here's the simple way and codes you can upload [images] into your assets folder
In Controller
public function upd_gallery(){
$file = $this->input->post('img_name').".jpg";
move_uploaded_file($_FILES['images']['tmp_name'], './wheretosave/etc/etc'.$file);
redirect( base_url().'gallery');
}
Set application -> config -> routes
$route['gallery/upload2'] = 'gallery/upd_gallery';
Put this to your view
<?php
$ff = './where-to-save/etc/'.$this->input->post('img_name').'.jpg';
?>
<form action="<?= base_url()?>gallery/upload2" method="post" enctype="multipart/form-data">
<div class="form-group">
<input type="text" class="form-control" name="img_name" required="required">
</div>
<div class="form-group">
<input type="file" class="form-control" name="images">
</div>
<div class="form-group">
<button type="submit" class="btn btn-common" value="Update"> Upload</button>
</div>
</div>
</div>
Of course, this way is very simple. You just have to name your image and save it
Saving image in database is NOT good practice. You can use following code to store files on your server's file system.
$userfile= $this->input->post('userfile'); //gets image name only
if ($_FILES['userfile']['name'] != '') { //to check if you've selected any file
$path = './path/to/folder';
$config['overwrite'] = FALSE;
$config['encrypt_name'] = FALSE;
$config['remove_spaces'] = TRUE;
$config['upload_path'] = $path;
$config['allowed_types'] = 'jpg|png|gif|jpeg';
$config['max_size'] = '0';
if (!is_dir($config['upload_path']))
die("THE UPLOAD DIRECTORY DOES NOT EXIST");
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile')) {
return "UPLOAD ERROR ! " . $this->upload->display_errors();
}
else {
$filepath = $this->upload->data();
$doc_path = $filepath['file_name'];
return $doc_path;
}
}

Yii file field posting empty values

I am a newbie in Yii, and I am trying to make an upload form in Yii, Please i need help.
Once the form post data to the controller every other post value is posted except for the file value.
i even tried checking for Errors with var_dump($model->image); and it returned this Error string '' (length=0) specifying an empty string like an image wasn't even posted at all.
This is my controller
class TestController extends Controller
{
public function actionIndex()
{
$model=new Test;
if(isset($_POST['Test']))
{
$model->attributes=$_POST['Test'];
if($model->save()){
var_dump($model->getErrors());
if ($model->image){
var_dump($model->image);
$uploadedFile=CUploadedFile::getInstance($model,'image');
$fileName = date("Y_m_d_H_i_s").$uploadedFile;
$model->image = $fileName;
if(!empty($uploadedFile)) // check if uploaded file is set or not
{
$uploadedFile->saveAs(Yii::getPathOfAlias('webroot').'/imagefolder/'.$fileName);
}
}
}
}
}
}
And this is my View
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'test-form',
'htmlOptions' => array('enctype' => 'multipart/form-data'),
'enableAjaxValidation'=>false,
)); ?>
<?php echo CHtml::activeFileField($model,'image',array('id'=>'primaryupload')); ?>
<?php echo CHtml::submitButton($model->isNewRecord ? 'UPLOAD' : 'UPLOAD',array('id'=>'submit','class'=>'btn')); ?>
<?php $this->endWidget(); ?>
Any help will be appreciated. Because i am really frusrated at this point.
If you are only new to Yii and not in PHP, than you may know that uploaded files goes via $_FILES global variable and not via $_POST global variable. So to get uploaded file, you use
$uploadedFile = CUploadedFile::getInstance($model, 'image');
So your final code looks like this:
$post = Yii::app()->request->getPost('Test');
if ($post) {
$model->attributes = $post;
$uploadedFile = CUploadedFile::getInstance($model, 'image');
if ($uploadedFile) {
$imageName = date("Y_m_d_H_i_s").$uploadedFile->name;
$model->image = $imageName;
if ($model->save()) {
$uploadedFile->saveAs(Yii::getPathOfAlias('webroot').'/imagefolder/'.$imageName );
}
}
I think you should use $_FILES['image'] instead of $model->image.
As an option, you can "hardcode" file attribute in your form. Just:
<input type="file" id="yourid" name="yourname" />
Then in YourController, where you are parsing your POST data you could directly access to $_FILES['yourname'].
Not an elegant way, but simple and fast.
P.S.: if you are using $this->beginWidget in your view, then you should add to parameters
$this->beginWidget('CActiveForm', array(
...
'htmlOptions'=>array(
'enctype'=>'multipart/form-data'
),
));

Yii Framework store/save submitted file to images folder

Hi, for the past 2 days i've been reading and reading lots of tutorials about saving files to folders in Yii, and neither of them have worked so far. I have the folowing form:
<div class="form">
<?php $form = $this->beginWidget('CActiveForm', array(
'htmlOptions' => array('enctype' => 'multipart/form-data')
)); ?>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'Binaryfile'); ?>
<?php echo $form->fileField($model,'uploadedFile'); ?>
<?php echo $form->error($model,'uploadedFile'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>
</div>
endWidget(); ?>
The file field submits the code to a BLOB field in mysql database.
The Controller is as follows:
public function actionCreate()
{
$model=new Estudos;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Estudos']))
{
$model->attributes=$_POST['Estudos'];
$model->binaryfile = CUploadedFile::getInstance($model,'binaryfile'); // grava na bd no campo binaryfile
// $model->binaryfile->saveAs(Yii::app()->params['uploadPath']);
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
And the Model is this one:
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('fileName', 'length', 'max'=>100),
array('fileType', 'length', 'max'=>50),
array('binaryfile', 'safe'),
// The following rule is used by search().
// #todo Please remove those attributes that should not be searched.
array('id, fileName, fileType, binaryfile', 'safe', 'on'=>'search'),
);
}
public $uploadedFile;
// Gravar imagem na base de dados - cria blob field
public function beforeSave()
{
if ($file = CUploadedFile::getInstance($this, 'uploadedFile'))
{
$this->fileName = $file->name;
$this->fileType = $file->type;
$this->binaryfile = file_get_contents($file->tempName);
}
return parent::beforeSave();
}
The code works fine to store a file as a BLOB field, but i need to change the code to store the file in images folder and next to display links that permits to open the file (pdf file) in any browser.
To store the file in images folder i tryed saveAs() in my controller actionCreate but Yii freezes and the webpage becames blank with no error, just blank.
**Anyone can help me... I need this very very much. Many thanks in advance. **
check this link,,in this link say how do it...
http://www.yiiframework.com/wiki/2/how-to-upload-a-file-using-a-model/
Finally i've figured it by myself. The answer was rather simple, but took me 4 days to write it.
In my actionCreate() i did:
public function actionCreate()
{
$model=new Estudos;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Estudos']))
{
$model->attributes=$_POST['Estudos'];
$model->uploadedFile=CUploadedFile::getInstance($model,'uploadedFile');
if($model->save())
$model->uploadedFile->saveAs("pdfs/".$model->uploadedFile,true);
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
**That way the saveAs() function worked like a charm and now saves my submited files in the pdfs folder.
The next step is to try and figure out how to create links for all files submitted to pdfs folder.
Maybe with a foreach() loop.
Best regards...**

YII file upload not working

Hi I am attempting to upload a file and write it to the database using YII, but nothing is happening at all, Its neither saving the file nor name saving to DB.
My View...
<div class="row">
<div class="span4"><?php echo $form->labelEx($model,'slider_image'); ?></div>
<div class="span5"><?php echo $form->fileField($model,'slider_image'); ?></div>
<div class="span3"><?php echo $form->error($model,'slider_image'); ?></div>
</div>
My Model for validation...
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
//more rules
array('slider_image', 'file', 'types'=>'jpg, gif, png', 'allowEmpty'=>true),
//more rules
);
}
Controller:
public function actionEdit()
{
$id = Yii::app()->getRequest()->getQuery('id');
$model = CustomPage::model()->findByPk($id);
if (!($model instanceof CustomPage))
{
Yii::app()->user->setFlash('error',"Invalid Custom Page");
$this->redirect($this->createUrl("custompage/index"));
}
if(isset($_POST['CustomPage']))
{
$model->attributes = $_POST['CustomPage'];
if (CUploadedFile::getInstance($model,'slider_image')) {
$model->slider_image=CUploadedFile::getInstance($model,'slider_image');
}
if ($model->validate())
{
if ($model->deleteMe)
{
$model->delete();
Yii::app()->user->setFlash('info',"Custom page has been deleted");
$this->redirect($this->createUrl("custompage/index"));
}
else {
$model->request_url = _xls_seo_url($model->title);
if (!$model->save())
Yii::app()->user->setFlash('error',print_r($model->getErrors(),true));
else
{
if (CUploadedFile::getInstance($model,'slider_image')) {
$model->slider_image->saveAs(Yii::app()->baseUrl.'images/'.$model->slider_image);
}
Yii::app()->user->setFlash('success',
Yii::t('admin','Custom page updated on {time}.',array('{time}'=>date("d F, Y h:i:sa"))));
$this->beforeAction('edit'); //In case we renamed one and we want to update menu
}
}
}
}
$this->render('edit',array('model'=>$model));
}
I attempted to die; after if (CUploadedFile::getInstance($model,'slider_image')) and nothing is happening, so it seems its not recognising it at all.
Thank you.
I think you're missing a minor directive in your view
Check to confirm that your form tag has the attribute "enctype"
i.e. <form action="" method="post" enctype="multipart/form-data">...</form>
TO set this in CActiveForm, do:
<?php $form = $this->widget('CActiveForm', array(
'htmlOptions'=>array('enctype'=>'multipart/form-data')
));?>

YII file upload not adding to database using form

Im attempting to add a file upload field to a form in YII, while its succesfully submitting and uploading the file to the correct folder, its not adding anything to the database.
Im only learning this platform so any guidance would be great.
Here is my view...
<div class="row">
<div class="span4"><?php echo $form->labelEx($model,'slider_image'); ?></div>
<div class="span5"><?php echo $form->fileField($model,'slider_image'); ?></div>
<div class="span3"><?php echo $form->error($model,'slider_image'); ?></div>
</div>
Here is my controller...
public function actionEdit() {
$id = Yii::app()->getRequest()->getQuery('id');
$model = CustomPage::model()->findByPk($id);
if (!($model instanceof CustomPage)) {
Yii::app()->user->setFlash('error',"Invalid Custom Page");
$this->redirect($this->createUrl("custompage/index"));
}
if(isset($_POST['CustomPage'])) {
$model->attributes = $_POST['CustomPage'];
$model->image=CUploadedFile::getInstance($model,'slider_image');
if ($model->validate()) {
if ($model->deleteMe) {
$model->delete();
Yii::app()->user->setFlash('info',"Custom page has been deleted");
$this->redirect($this->createUrl("custompage/index"));
} else {
$model->request_url = _xls_seo_url($model->title);
if (!$model->save()) {
Yii::app()->user->setFlash('error',print_r($model->getErrors(),true));
} else {
$model->image->saveAs(Yii::app()->baseUrl.'images/'.$model->image);
Yii::app()->user->setFlash('success',
Yii::t('admin','Custom page updated on {time}.',array('{time}'=>date("d F, Y h:i:sa"))));
$this->beforeAction('edit'); //In case we renamed one and we want to update menu
}
}
}
}
}
and my model
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
// other rules
array('slider_image', 'file', 'types'=>'jpg, gif, png'),
);
}
The form itself overall is working fine, unfortunately I dont understand how YII adds to the database
Thanks
Adrian
EDIT: Ive also obviously got a slider_image field in that table
What your Controller code would do is save the file name of the upoloaded file in your database table. Another thing is: your code:
$model->image=CUploadedFile::getInstance($model,'slider_image');
is referring to the wrong attribute. I think it should be:
$model->slider_image=CUploadedFile::getInstance($model,'slider_image');
Finally, you need to call $model->slider_image->save('path.to.file'); in order to save the file to disk
I believe you get stock at $model->validate(). Because you do copy image above this line copying is fine but you do not go through validation so it never saves to DB.
var_dump($model->validate()); to see what is going on...

Categories