How can i upload image from front-end in magento? - magento

I am trying to upload single image from front-end in my custom module. This is my form in test/template/test.phtml
<form action="<?php echo Mage::getUrl('text/index/save') ?>" method="post" enctype="multipart/form-data">
<label for="sb_link">Image</label>
<input type="file" id="bs_image" name="bs_image" required="true"/>
<input type="submit" value="Submit" />
Here is my controller where i am uploading images in media folder and saving name in databse.
<?php
public function saveAction() {
echo $path = Mage::getBaseDir() . '/test';
if (!file_exists($path)) {
mkdir($path, 777, true);
}
try {
$fname = $_FILES['test']['name'];
$uploader = new Varien_File_Uploader('test');
$uploader->setAllowedExtensions(array('png', 'gif', 'jpeg', 'docx'));
$uploader->setAllowCreateFolders(true);
$uploader->setAllowRenameFiles(false);
$uploader->setFilesDispersion(false);
$uploader->save($path, $fname);
} catch (Exception $e) {
echo 'Error Message: ' . $e->getMessage();
}
$contact = Mage::getModel('test/test');
$contact->setData('bs_image', $bs_image);
$contact->save();
$this->_redirectReferer();
}
I am getting this error.Error Message: File was not uploaded.
Thanks

I have checked your code. In form you use the name as bs_image for image field. But in controller you get the post file as $_FILES['test']['name'];. Change this to $_FILES['bs_image']['name']; .

Make sure that you have put end form tag in your file.
You need to access file name like this
$fname = $_FILES['bs_image']['name'];

Related

File does not exist (ncjoes/office-converter, laravel)

i was using ncjoes/office-converter, trying to upload .docx and convert it to .pdf, but it occurred error when it converts to .pdf
the error shows NcJoes\OfficeConverter\OfficeConverterException
File does not exist --test.docx
view
<form action="/notes" method="POST" role="form" enctype="multipart/form-data">
#csrf
#method('POST')
<div>
<label for="title">title:</label>
<input id="title" name="title">
</div>
<div>
<label for="topdf">upload:</label>
<input type="file" id="topdf" name="topdf">
</div>
<button type="submit" class="btn-sm btn-primary">add</button>
</form>
controller
public function store(Request $request)
{
$validatedData = $request->validate([
'topdf' => 'required|mimes:docx',
'title'=>'required'
]);
$Name = str_replace(" ","",$request->input('title'));
$FileName = $Name . '.' . $request->topdf->extension();
$request->topdf->move(public_path('pdf'), $FileName);
$converter = new OfficeConverter($FileName);
//$fin=$converter->convertTo('output-file.pdf');
//$fin->move(public_path('pdf'), $FileName);
}
i think $converter = new OfficeConverter($FileName); was wrong, but idk how to fix ;;
First upload the file this way:
$file = $request->file('topdf')->store('pdf');
$path = Storage::path($file);
And then, try to access the file and convert via the $path variable:
$converter = new OfficeConverter($path);

Input type submit won't trigger when it's clicked

I have trouble with my code, I want to create an upload button to upload my .xlsx file, but it won't trigger even when I try to click it.
My view.php :
<form action="<?php echo base_url("index.php/fin/cost_control/workingcanvas/import"); ?>" method="post" id="import_form" enctype="multipart/form-data">
<p><label>Pilih File Excel</label>
<input type="file" name="file" id="file" required accept=".xls, .xlsx" /></p>
<br />
<input type="submit" id="import" name="import" value="Import" class="btn btn-info" />
</form>
My controller:
public function import(){
include APPPATH.'third_party/PHPExcel/PHPExcel.php';
$excelreader = new PHPExcel_Reader_Excel2007();
$loadexcel = $excelreader->load('excel/'.$this->filename.'.xlsx');
$sheet = $loadexcel->getActiveSheet()->toArray(null, true, true ,true);
$numrow = 1;
foreach($sheet as $row){
if($numrow > 1){
array_push($data, array(
'nis'=>$row['A'],
'nama'=>$row['B'],
'jenis_kelamin'=>$row['C'],
'alamat'=>$row['D'],
));
}
$numrow++;
}
$this->SiswaModel->insert_multiple($data);
redirect("Siswa");
}
and my model:
public function insert_multiple($data){
$this->db->insert_batch('siswa', $data);
}
I've tried with adding some part on autoload such as
$autoload['helper'] = array('url','form','file');
Any suggestions or advice? Thanks.
first load form helper in autoload file of codeigniter or load manually
$autoload['helper'] = array('url'); // autoload
$this->load->helper->('form'); // manually loading form helper
you better use this
$attributes = array('enctype' => 'multipart/form-data');
echo form_open('index.php/fin/cost_control/workingcanvas/import', $attributes);
<your upload form code>
<?php echo form_close(); ?>
instead of tags
more info: https://codeigniter.com/user_guide/helpers/form_helper.html

Prevent duplicate entry in database Codeigniter

I would like to know how to prevent my upload function to insert duplicate entries into the database by using the uid.
public function upload(){
if(!empty($_FILES['uploaded_file']))
{
$path = FCPATH . "/file_attachments/signature_file/";
$path = $path . basename( $_FILES['uploaded_file']['name']);
$base64 = base64_encode(file_get_contents($_FILES['uploaded_file']['tmp_name']));
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path))
{
$data = array (
'uid' => $this->user->get_uid(),
'image' => $base64,
'name' => basename( $_FILES['uploaded_file']['name']),
);
$this->load->database('employee');
$this->db->insert('signatures', $data);
// echo "The file ". basename( $_FILES['uploaded_file']['name']).
// " has been uploaded";
$alert = "The file ". basename( $_FILES['uploaded_file']['name']).
" has been uploaded";
redirect(base_url() . "signature_uploader/search/?id=" . $alert);
}
else
{
// echo "There was an error uploading the file, please try again!";
$alert ="There was an error uploading the file, please try again!";
redirect(base_url() . "signature_uploader/search/?id=" . $alert);
}
}
}
Here's my view file. I haven't got the time to edit the unnecessary things in here. The problem is still that if it got duplicate entries the database error still shows up and that is what I'm preventing to do so. Cheers!
<div class="bod">
<div class="insta">
<form enctype="multipart/form-data" style="padding-top: 10px" name="exit_form" method="post" action="<?= base_url() ?>signature_uploader/upload">
<input type="hidden" name="uid" value="<?= $agent->get_uid() ?>" />
<input type="hidden" name="gid" value="<?= $agent->get_gid() ?>" />
<input type="hidden" name="fname" value="<?= $agent->get_fname() ?>" />
<input type="hidden" name="lname" value="<?= $agent->get_lname() ?>" />
<div style="text-align: center; font-size: 25pt; margin-bottom: 15px">Signature Uploader</div>
<table width="105%">
<tr>
<td width="40%"><strong>Name: </strong><input class="textinput" disabled="disabled" type="text" name="full_name" id="textfield3" size="35" value="<?= $agent->get_fullName() ?>" /></td>
<tr/>
<tr>
<td><label>Upload Image File:</label><br /> <input name="uploaded_file" type="file" accept=".png" required/>
</tr>
<table/>
<br />
<input type="submit" value="Submit" class="button1" />
</form>
<br/>
</div>
You can use from Codeigniter form validation to prevent from duplicate entry:
at first you must get the uid in the form view like this:
<input type="hidden" name="uid" value="<?php echo $this->user->get_uid() ?>">
and then in your controller:
public function upload(){
if(!empty($_FILES['uploaded_file']))
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('uid', 'UID', 'is_unique[signatures.uid]');
if ($this->form_validation->run() == FALSE)
{
// Your Code if the uid is duplicate
$alert ="Could't upload because of duplicate entry!";
redirect(base_url() . "signature_uploader/search/?id=" . $alert);
}
else
{
// Your Code if the uid is unique
$path = FCPATH . "/file_attachments/signature_file/";
$path = $path . basename( $_FILES['uploaded_file']['name']);
$base64 = base64_encode(file_get_contents($_FILES['uploaded_file']['tmp_name']));
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
$data = array (
'uid' => $this->input->post('uid'),
'image' => $base64,
'name' => basename( $_FILES['uploaded_file']['name']),
);
$this->load->database('employee');
$this->db->insert('signatures', $data);
// echo "The file ". basename( $_FILES['uploaded_file']['name']).
// " has been uploaded";
$alert = "The file ". basename( $_FILES['uploaded_file']['name']).
" has been uploaded";
redirect(base_url() . "signature_uploader/search/?id=" . $alert);
} else{
// echo "There was an error uploading the file, please try again!";
$alert ="There was an error uploading the file, please try again!";
redirect(base_url() . "signature_uploader/search/?id=" . $alert);
}
}
}
}
Either you can check weather such file exists or not, but normally while creating a code which uploads file, has a function which will generate unique name for each file that we upload. So in such cases it will have duplicate entries with different name.
Only way i see is to create a function that will check weather the file name already exists in database.

How to validate a form in Kohana 3.3.1

I'm trying to validate a form but it doesn't show validation errors and if field is empty, it saves. How to validate form?
My code is:
public function action_upload()
{
if($_POST) {
$name = array(
'name' => Arr::get($_POST, 'name')
);
$validate = Validation::factory($name)
->rule('name', 'not_empty');
try {
$save = Model_Offers::Save($this->user['user_id'], $name);
}
catch (ORM_Validation_Exception $e)
{
$result = $e->errors('models');
echo '<pre>';
print_r($result);
exit;
}
}
}
My view is:
<form id="myForm" action="<?php echo URL::base()?>user/upload" method="post" enctype="multipart/form-data">
<div class="input-group">
<label for="file">Name: </label>
<input type="text" name="name" id="name"><br>
</div>
</form>
You created the validation object, but you forgot to actually apply the rules you assigned. Simply do this by calling
$validate->check()
It'd be best to put this in an if-else statement
if($validate->check()){
//Save object
}
else{
//Get errors (use $validate->errors())
}
Hope that helps! :)

File (picture) Upload not working

Okay so I just basically got this code online.
It works locally (to upload a file), but it doesn't wanna work on the website.
(I've already put the permissions at 0777, for the folder, but it still won't upload.
<header>
<?php
function UploadOne($fname)
{
$uploaddir = 'pictures/';
if (is_uploaded_file($fname['tmp_name']))
{
$filname = basename($fname['name']);
$uploadfile = $uploaddir . basename($fname['name']);
if (move_uploaded_file ($fname['tmp_name'], $uploadfile))
$res = "File " . $filname . " was successfully uploaded and stored.<br>";
else
$res = "Could not move ".$fname['tmp_name']." to ".$uploadfile."<br>";
}
else
$res = "File ".$fname['name']." failed to upload.";
return ($res);
}
?> </header>
<body>
<?php
if ($_FILES['picture']['name'] != "")
{
$res = UploadOne($_FILES['picture']);
$filname = $_FILES['picture']['name'];
echo ($res);
}
?>
<h1>UPLOADING FILES</h1>
<form name="fupload" enctype="multipart/form-data" action="upfiles.php" method="post">
<input type="file" name="picture" />
<input type="submit" value="Submit" />
</form>
</body>

Resources