I have to upload a mp3 file type with codeigniter upload library.
I use the following code.
But it doesn't work.
The class controller code:
<?php
class Upload extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
public function index()
{
$this->load->view('upload_form', array('error' => ' ' ));
}
public function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|mp3';
$config['max_size'] = 0;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
}
?>
When the file type is jpg or like that, this code correctly works and the jpg file is uploaded.
But when I try to upload an mp3 file, the file doesn't upload.
And not any error shows up.
How can I do this?
add this code on mime.php (application/config/mimes.php) file.
This is right answer :
OLD:
'mp3' => array('audio/mpeg', 'audio/mpg', 'audio/mpeg3','audio/mp3')
NEW:
'mp3' => array('audio/mpeg', 'audio/mpg','audio/mpeg3','audio/mp3','application/octet-stream')
Thank You
Add in your file mimes.php (application/config/mimes.php) the 'application/octet-stream' in each array of mime you want to do upload, example;
OLD: 'mp3' => array('audio/mpeg', 'audio/mpg', 'audio/mpeg3', 'audio/mp3')
MEW: 'mp3' => array('audio/mpeg', 'audio/mpg', 'audio/mpeg3', 'audio/mp3', 'application/octet-stream')
Related
I'm using codeigniter and phpspreadsheet to import the Excel file data. Now, in my code can read the Excel contents as well but I got error when trying to transfer DATA and display it on views. Please help to adv.
1. Error code.
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: sheetData
Filename: views/upload_view.php
Line Number: 18
3. Controller code
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
//Load plugin
require (APPPATH .'third_party\vendor\autoload.php');
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\IReadFilter;
class Upload extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
public function index()
{
$this->load->view('header_view');
$this->load->view('menu_view');
$this->load->view('upload_view');
}
function do_upload()
{
$config['upload_path'] = './uploads';
$config['allowed_types'] = 'xls|xlsx';
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('upload_file')){
$error = array('error' => $this->upload->display_errors());
var_dump ($error);
}
else{
$data = array('upload_data' => $this->upload->data());
$full_path = $data['upload_data']['full_path'];
//---------Config read file content----------//
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx(); //Excel 2007 or higher
//$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xls(); //Excel 2003
$spreadsheet = $reader->load($full_path);
$sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
//var_dump('<pre>');
//var_dump($sheetData);
$this->load->view('header_view');
$this->load->view('menu_view');
$this->load->view('upload_view', $sheetData);
}
}
}
/* End of file Upload.php */
/* Location: ./application/controllers/Upload.php */
2. View code
<?php
foreach ($sheetData as $value) {
echo $value -> A;
}
?>
Try this way:
$dataarr = array();
$dataarr['sheetData'] = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
$this->load->view('header_view');
$this->load->view('menu_view');
$this->load->view('upload_view', $dataarr);
I think it will help you.
Usually we can get the form data in Codeigniter by using $this->input->get('field_name') or $this->input->post('field_name') and that's fine.
In raw PHP we use $_FILES["fileToUpload"]["name"] to get the file name that the user trying to upload.
My question is: Is there any Codeigniter way to get the name of the file that needs to be uploaded?
I am trying to say that i need to get the file name that the user is trying to upload before trying to save it in my server using Codeigniter library instead of using raw PHP global $_FILES variable.
<?php
class Upload extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
public function index()
{
$this->load->view('upload_form', array('error' => ' ' ));
}
public function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
// get the user submitted file name here
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
}
?>
$upload_data = $this->upload->data();
$file_name = $upload_data['file_name'];
Here is the 2 version doc is for 2 and for 3
if you want to get the file name in backend:
$this->upload->file_name It will work based on system/library/upload.php
this function.
public function data()
{
return array (
'file_name' => $this->file_name,
'file_type' => $this->file_type,
...
);
}
If you need to get file name...
Before saving to server... you have work in javascript
<?php echo "<input type='file' name='userfile' size='20' onchange='changeEventHandler(event);' />"; ?>
onchange event in javascript:
<script>
function changeEventHandler(event){
alert(event.target.value);
}
</script>
$data = array('upload_data' => $this->upload->data());
// use file_name within the data() the final code will be
$data = array('upload_data' => $this->upload->data('file_name'));
I'm making a website on the CodeIgniter framework so users can upload products on the website to the database. I'm trying to make a function so users can upload pictures to my database but its not really working.
Here some info:
DB table name: products
The DB table column name that I want the pictures to be stored in: product_foto
picture folder: upload
My controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Product extends CI_Controller {
var $data = array();
public function __construct()
{
parent::__construct();
$this->load->model('product_model');
$this->load->helper(array('form', 'url'));
}
public function product_form()
{
$save = array(
'product_naam' => $this->input->post('product_naam'),
'product_beschrijving' => $this->input->post('product_beschrijving'),
'product_categorie' => $this->input->post('product_categorie'),
'ophaal_plaats' => $this->input->post('ophaal_plaats'),
'product_foto' => $this->input->post('product_foto'),
'date_created' => date('Y-m-d'),
'date_updated' => date('Y-m-d')
);
$this->product_model->saveProduct($save);
redirect('https://kadokado-ferran10.c9users.io/AlleCadeausController');
}
public function upload(){
$config['upload_path'] = './upload/';
$config['allowed_types'] = 'jpg|jpeg|png';
$this->load->library('upload', $config);
if(!$this->upload->do_upload('file')){
$this->db->insert('products', array(
'product_foto' => $this->upload->file_name
));
$error = array('error'=>$this->upload->display_errors());
$this->load->view('product_form', $error);
}else{
$file_data = $this->upload->data();
$data['img'] = base_url().'/upload/'.$file_data['file_name'];
header('location:https://kadokado-ferran10.c9users.io/Product/');
}
}
}
My model file:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Product extends CI_Controller {
var $data = array();
My view file:
<?php echo form_open_multipart('Product/upload'); ?>
<input type="file" name="userfile" />
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name">
</div>
<input type="submit" name="submit" value="test" />
</form>
When I submit the form the picture only gets added to the upload folder but it doesn't get added into the database column..
Change your upload() function as follow
public function upload(){
$config['upload_path'] = './upload/';
$config['allowed_types'] = 'jpg|jpeg|png';
$this->load->library('upload', $config);
if(!$this->upload->do_upload('userfile')){
$error = array('error'=>$this->upload->display_errors());
$this->load->view('product_form', $error);
}else{
$file_data = $this->upload->data();
$this->db->insert('products', array(
'product_foto' => $file_data['file_name']
));
$data['img'] = base_url().'/upload/'.$file_data['file_name'];
header('location:https://kadokado-ferran10.c9users.io/Product/');
}
}
I'd like to ask a question please.
I have inside my model a method that holds both file uploading and image manipulation. The code works fine, but the only problem is I can't figure out how to get the upload error back in the controller in order to pass it to the view and display it to the user.
This is the code in my model:
class Foo_Model extends CI_Model
{
public function do_upload(){
$id = intval($this->input->post('id'));
$config = array(
'upload_path' => './uploads/files/',
'allowed_types' => 'gif|jpg|png',
'max_size' => '2048',
'max_width' => '800',
'max_heigth' => '300',
'overwrite' => true,
'file_name' => 'file_'.$id, // e.g. file_10.jpg
);
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('file') ) {
return $this->upload->display_errors();
} else {
// file uploaded successfully
// now lets create some thumbs
$upload_file = $this->upload->data();
if ($upload_file['is_image']) {
$config['image_library'] = 'gd2';
$config['source_image'] = $upload_file['file_name'];
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 75;
$config['height'] = 50;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
}
// uploading and resizing was done
return $upload_file;
// return true;
}
}
}
Code in my controller
public function upload(){
$this->foo_model->do_upload();
// need to get the upload error (if any occured) or the upload data
// how can I get them back from function of the model?
$this->load->view('form_upload', $data);
}
You are return errors from Model method so hold returned data in variable and check that is error or file_data
public function upload(){
$upload_data = $this->foo_model->do_upload();
//upload data will be return in array format
if(is_array($upload_data)){
$data['upload_file_info'] = $upload_data
}else{ /*error as string so if not array then always error*/
$data['error'] = $upload_data;
}
$this->load->view('form_upload', $data);
}
I'm having this function inside my Album_Model:
public function upload($album_id, $album){
$album= strtolower($album);
$upload_config = array(
'upload_path' => './uploads/'.$album,
'allowed_types' => 'jpg|jpeg|gif|png',
'max_size' => '2000',
'max_width' => '680',
'max_height' => '435',
);
$this->load->library('upload', $upload_config);
// create an album if not already exist in uploads dir
// wouldn't make more sence if this part is done if there are no errors and right before the upload ??
if (!is_dir('uploads')) {
mkdir('./uploads', 0777, true);
}
if (!is_dir('uploads/'.$album)) {
mkdir('./uploads/'.$album, 0777, true);
}
if (!$this->upload->do_upload('imgfile')) {
// upload failed
return array('error' => $this->upload->display_errors('<span>', '</span>'));
} else {
// upload success
$upload_data = $this->upload->data();
return true;
}
}
So what this basicly does is to upload images to an album. Also if the folder album does not exist already, it creates a new album.
I was doing some tests and found out something that might be a small bug. While I was forcing my form to do some invalid upload attempts and the upload fails, as expected, but the album folder (suppose the album folder doesn't exist) is still created.
Whouldn't make more sence to create the album folder if there are no erros and right before uploading the image and if yes how can I fix this??
You have set a flag for checking the directory existence. I have changed your code to make it work as per your need.
<?php
public function upload($album_id, $album)
{
$album = strtolower($album);
$upload_config = array('upload_path' => './uploads/' . $album, 'allowed_types' =>
'jpg|jpeg|gif|png', 'max_size' => '2000', 'max_width' => '680', 'max_height' =>
'435', );
$this->load->library('upload', $upload_config);
// create an album if not already exist in uploads dir
// wouldn't make more sence if this part is done if there are no errors and right before the upload ??
if (!is_dir('uploads'))
{
mkdir('./uploads', 0777, true);
}
$dir_exist = true; // flag for checking the directory exist or not
if (!is_dir('uploads/' . $album))
{
mkdir('./uploads/' . $album, 0777, true);
$dir_exist = false; // dir not exist
}
else{
}
if (!$this->upload->do_upload('imgfile'))
{
// upload failed
//delete dir if not exist before upload
if(!$dir_exist)
rmdir('./uploads/' . $album);
return array('error' => $this->upload->display_errors('<span>', '</span>'));
} else
{
// upload success
$upload_data = $this->upload->data();
return true;
}
}
?>
THE ACCEPTED ANSWER IS NOT THE RIGHT WAY!!!
The right way is to extend the Upload library
The code:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
* File Uploading Class Extension
*
* #package CodeIgniter
* #subpackage Libraries
* #category Uploads
* #author Harrison Emmanuel (Eharry.me)
* #link https://www.eharry.me/blog/post/my-codeigniter-upload-extension/
*/
class MY_Upload extends CI_Upload {
/**
* Validate Upload Path
*
* Verifies that it is a valid upload path with proper permissions.
*
* #return bool
*/
public function validate_upload_path()
{
if ($this->upload_path === '')
{
$this->set_error('upload_no_filepath', 'error');
return FALSE;
}
if (realpath($this->upload_path) !== FALSE)
{
$this->upload_path = str_replace('\\', '/', realpath($this->upload_path));
}
if ( ! is_dir($this->upload_path))
{
// EDIT: make directory and try again
if ( ! mkdir ($this->upload_path, 0777, TRUE))
{
$this->set_error('upload_no_filepath', 'error');
return FALSE;
}
}
if ( ! is_really_writable($this->upload_path))
{
// EDIT: change directory mode
if ( ! chmod($this->upload_path, 0777))
{
$this->set_error('upload_not_writable', 'error');
return FALSE;
}
}
$this->upload_path = preg_replace('/(.+?)\/*$/', '\\1/', $this->upload_path);
return TRUE;
}
}
How to use:
Simply create application/libraries/MY_Upload.php and paste the code above in it.
That's all!
More info:
The GitHub Gist.
My blog post on Eharry.me
NOTE:
This extension is compatible with CodeIgniter 3.x and 2.x versions.
The way you have it it will always make the directory if it does not exist.
To answer your question.. yes, it would make more sense, to create the folder right before uploading.
Try putting this:
if (!is_dir('uploads')) {
mkdir('./uploads', 0777, true);
}
if (!is_dir('uploads/'.$album)) {
mkdir('./uploads/'.$album, 0777, true);
}
Inside this:
if (!$this->upload->do_upload('imgfile')) {
// upload failed
return array('error' => $this->upload->display_errors('<span>', '</span>'));
} else {
// put if statements here.
// upload success
$upload_data = $this->upload->data();
return true;
}
So it would look like this:
if (!$this->upload->do_upload('imgfile')) {
// upload failed
return array('error' => $this->upload->display_errors('<span>', '</span>'));
} else {
if (!is_dir('uploads')) {
mkdir('./uploads', 0777, true);
}
if (!is_dir('uploads/'.$album)) {
mkdir('./uploads/'.$album, 0777, true);
}
// upload success
$upload_data = $this->upload->data();
return true;
}
If I understand you correctly this should do what you want.
Hope it helps.