How can I compress image in Laravel not resize? - laravel

I want to save compressed image in laravel upload. I have found a package called "intervention/image". But it has resize functionality not compress.

You can simply make this:
public function compress($source, $destination, $quality = 75) {
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($source);
} elseif ($info['mime'] == 'image/gif') {
$image = imagecreatefromgif($source);
} elseif ($info['mime'] == 'image/png') {
$image = imagecreatefrompng($source);
}
imagejpeg($image, $destination, $quality);
return $destination;
}
The destination can be same the source

<form action="{{route('resizeImagePost')}}" method="POST" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="col-md-12">
<br/>
<input type="file" name="image" placeholder="image" class ="image">
</div>
<div class="col-md-12">
<br/>
<button type="submit" class="btn btn-success">Upload Image</button>
</div>
</div>
</form>
public function resizeImagePost(Request $request)
{
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$image = $request->file('image');
$upload_imagename = time().'.'.$image->getClientOriginalExtension();
$upload_url = public_path('/images').'/'.$upload_imagename;
$filename = $this->compress_image($_FILES["image"]["tmp_name"], $upload_url, 40);
return back()
->with('success','Image Upload successful');
}
public function compress_image($source_url, $destination_url, $quality) {
$info = getimagesize($source_url);
if ($info['mime'] == 'image/jpeg')
$image = imagecreatefromjpeg($source_url);
elseif ($info['mime'] == 'image/gif')
$image = imagecreatefromgif($source_url);
elseif ($info['mime'] == 'image/png')
$image = imagecreatefrompng($source_url);
imagejpeg($image, $destination_url, $quality);
return $destination_url;
}

Related

Impossible to upload file with buefy upload

I'm creating a website and now I try to use my upload file system. I test it with postman and it works perfectly. But when I try to use with my website page, it not works.
Backend : I use Lumen
Frontend : I use Buefy
The upload function into UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;
use Illuminate\Support\Facades\DB;
class UserController extends Controller
{
public function uploadImageIntoUser(Request $request, $id){
//try{
$user = User::findOrFail($id);
if ($user->id == Auth::id()) {
$url = json_decode($this->uploadImage($request, $id)->getContent(), true);
$newRequest = new Request();
$newRequest->replace(['picture' => $url['data']['image'] ]);
return $this->update($id, $newRequest);
}
return response()->json(['message' => 'You not have the right to do this'], 412);
/*}catch (\Exception $e){
return response()->json(['message' => 'User not found'], 404);
}*/
}
}
The upload function into my Controller.php
<?php
namespace App\Http\Controllers;
use Laravel\Lumen\Routing\Controller as BaseController;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Galerie;
use Illuminate\Support\Str;
class Controller extends BaseController
{
//Upload image
public function uploadImage(Request $request, $id)
{
try{
$this->validate($request, [
'folder' => array(
'required',
'alpha')
]);
$folder = $request->input('folder');
if(strcmp($folder, "user") !== 0 && strcmp($folder, "article") !== 0 && strcmp($folder, "galerie") !== 0){
return response()->json(['message' => 'Incorrect folder name : choose between user, article and galerie'], 409);
}
} catch (\Exception $e) {
return response()->json(['message' => 'Incorrect folder name : only in lowercase'], 409);
}
$response = null;
$user = (object) ['image' => ""];
if ($request->hasFile('image')) {
$original_filename = $request->file('image')->getClientOriginalName();
$original_filename_arr = explode('.', $original_filename);
$file_ext = end($original_filename_arr);
if($folder == 'user'){
$destination_path = './upload/user/';
}else if($folder == 'article'){
$destination_path = './upload/article/';
}else if($folder == 'galerie'){
$destination_path = './upload/galerie/';
}
$image = time() . '.' . $file_ext;
if ($request->file('image')->move($destination_path, $image)) {
if ($folder == 'user') {
$user->image = '/upload/user/' . $image;
}else if($folder == 'article'){
$user->image = 'upload/article/' . $image;
}else if($folder == 'galerie'){
$user->image = 'upload/galerie/' . $image;
$galerie = new Galerie;
$galerie->id = Str::uuid();
$galerie->url = $user->image;
$galerie->save();
}
return $this->responseRequestSuccess($user);
} else {
return $this->responseRequestError('Cannot upload file');
}
} else {
return $this->responseRequestError('File not found');
}
}
protected function responseRequestSuccess($ret)
{
return response()->json(['status' => 'success', 'data' => $ret], 200)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
protected function responseRequestError($message = 'Bad request', $statusCode = 200)
{
return response()->json(['status' => 'error', 'error' => $message], $statusCode)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}
Call my upload system from my profile page (called connexion.vue)
<template>
<section class="section">
<div class="container">
<p id="center-text" class="title">Informations Personnelles</p><br>
<b-notification v-if="error" type="is-warning">
{{ error }}
</b-notification>
<div class="columns">
<div class="column">
<img :src='baseURL + loggedInUser.picture'>
<b-field label="Modifier la photo de profil">
<b-field class="file is-secondary" :class="{'has-name': !!file2}">
<b-upload v-model="file2" class="file-label" rounded>
<span class="file-cta">
<b-icon class="file-icon" icon="upload"></b-icon>
<span class="file-label"><strong>Sélectionner un fichier à envoyer</strong></span>
</span>
<span class="file-name" v-if="file2">
{{ file2.name }}
</span>
</b-upload>
</b-field>
</b-field>
<b-button v-if="file2" type="is-secondary" #click="upload">Envoyer</b-button>
</div>
<div class="column">
<p class="title">{{ loggedInUser.pseudo }} <b-button #click="modifyPseudo" icon-right="pencil"/> </p><br v-if="!isModifyPseudo">
<form v-if="isModifyPseudo" method="post" #submit.prevent="sendModification">
<b-field label="Nouveau nom d'utilisateur" label-for="newPseudo">
<b-input id="newPseudo" v-model="newPseudo"></b-input>
</b-field>
<div class="control">
<button type="submit" class="button is-secondary is-fullwidth">
<strong>Modifier</strong>
</button>
</div><br>
</form>
<p class="subtitle">Adresse mail : {{ loggedInUser.email }} <b-button #click="modifyMail" icon-right="pencil"/> </p>
<form v-if="isModifyMail" method="post" #submit.prevent="sendModification">
<b-field label="Nouvelle adresse mail" label-for="newMail">
<b-input id="newMail" v-model="newMail" type="email"></b-input>
</b-field>
<div class="control">
<button type="submit" class="button is-secondary is-fullwidth">
<strong>Modifier</strong>
</button>
</div><br>
</form>
<p class="subtitle">Nationalité : {{ loggedInUser.nationality }} <b-button #click="modifyNation" icon-right="pencil"/> </p>
<form v-if="isModifyNation" method="post" #submit.prevent="sendModification">
<b-field label="Nouvelle nationalité" label-for="newNation">
<b-select expanded v-model="newNation" icon="earth">
<option
v-for="nation in nationalities"
:value="nation.code"
:key="nation.id">
{{ nation.name }}
</option>
</b-select>
</b-field>
<div class="control">
<button type="submit" class="button is-secondary is-fullwidth">
<strong>Modifier</strong>
</button>
</div><br>
</form>
</div>
</div>
</div>
</section>
</template>
<script>
import { mapGetters } from 'vuex'
import countries from '#/assets/countries.json';
export default {
middleware: 'auth',
computed: {
...mapGetters(['isAuthenticated', 'loggedInUser'])
},
data (){
return {
baseURL: 'http://localhost:8000/',
isModifyPseudo: false,
isModifyMail: false,
isModifyNation: false,
newPseudo: '',
newMail: '',
newNation: '',
nationalities: {},
error: '',
file2 : null,
}
},
methods: {
modifyPseudo() {
if(!this.isModifyPseudo){
this.newPseudo='';
}
this.isModifyPseudo = !this.isModifyPseudo;
},
modifyMail() {
if(!this.isModifyMail){
this.newMail='';
}
this.isModifyMail = !this.isModifyMail;
},
modifyNation() {
if(!this.isModifyNation){
this.newNation='';
}
this.isModifyNation = !this.isModifyNation;
},
async upload(){
try{
var formData = new FormData();
console.log(this.file2);
formData.append('image', this.file2);
const newPicture = await this.$axios.post('users/' + this.loggedInUser.id + '/picture', formData, {
headers: {'Content-Type': 'multipart/form-data'}
});
console.log(newPicture);
const updatedUser = {...this.$auth.user}
updatedUser.picture = newPicture.data.picture;
this.$auth.setUser(updatedUser)
this.file2 = null;
}catch (error){
//this.error = error.response.data.message;
console.log(error.response);
}
},
async sendModification(){
try{
if(this.isModifyPseudo){
const newPseudo = await this.$axios.put('users/' + this.loggedInUser.id, {
pseudo: this.newPseudo
});
const updatedUser = {...this.$auth.user}
updatedUser.pseudo = newPseudo.data.pseudo;
this.$auth.setUser(updatedUser)
this.newPseudo = '';
this.isModifyPseudo = false;
}
if(this.isModifyMail){
const newMail = await this.$axios.put('users/' + this.loggedInUser.id, {
email: this.newMail
});
const updatedUser = {...this.$auth.user}
updatedUser.email = newMail.data.email;
this.$auth.setUser(updatedUser)
this.newMail = '';
this.isModifyMail = false;
}
if(this.isModifyNation){
const newNation = await this.$axios.put('users/' + this.loggedInUser.id, {
nationality: this.newNation
});
const updatedUser = {...this.$auth.user}
updatedUser.nationality = newNation.data.nationality;
this.$auth.setUser(updatedUser)
this.newNation = '';
this.isModifyNation = false;
}
}catch(error){
this.error = error.response.data.message;
}
}
},
async mounted() {
try {
this.nationalities = countries;
} catch (err) {
throw err;
}
},
}
</script>
<style scoped>
img {
border-radius: 50%;
object-fit: cover;
height: 10em;
width: 10em;
}
.container #center-text {
text-align: center;
}
.file-label strong{
color: white;
}
</style>
And when I click on the send button, because I don't catch the error, it sends the error 500.
EDIT :
So into my upload function into my profile page (called connexion.vue) :
I replace that
var formData = new FormData();
console.log(this.file2);
formData.append('image', this.file2);
by this
var formData = new FormData();
console.log(this.file2);
formData.append('image', this.file2);
formData.append('folder', 'user');
and into my Controller.php file I replace this :
if($folder == 'user'){
$destination_path = './upload/user/';
}else if($folder == 'article'){
$destination_path = './upload/article/';
}else if($folder == 'galerie'){
$destination_path = './upload/galerie/';
}
by this
if($folder == 'user'){
$destination_path = storage_path('../public/upload/user/');
//$destination_path = './upload/user/';
}else if($folder == 'article'){
$destination_path = storage_path('../public/upload/article/');
//$destination_path = './upload/article/';
}else if($folder == 'galerie'){
$destination_path = storage_path('../public/upload/galerie/');
//$destination_path = './upload/galerie/';
}

[Codeigniter]Multiple upload cant insert to database and not uploading to directory

How to upload multiple images with Codeigniter 4.x ?
I tried to loop the do_upload function in my model but it's not working, and I tried another code that I got from GitHub but still, none of it works.
This is my view:
<div class="section-body">
<h2 class="section-title">Entry Group Passanger</h2>
<div class="row">
<div class="col-md-12">
<form action="<?= base_url('passanger/addgroup') ?>" method="POST" enctype="multipart/form-data">
<?php for($i=1;$i<=$pax['pax'];$i++) : ?>
<h5>Passanger ke-<?= $i ?></h5>
<div class="form-row">
<div class="col-md-6">
<label for="fullname">Fullname</label>
<input type="text" class="form-control" name="name[]">
<?= form_error('name', '<small class="text-danger pl-3">', '</small>'); ?>
</div>
<div class="col-md-6">
<label for="gender">Gender</label>
<select class="form-control select2-input" name="gender">
<option>-- Select Gender --</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select>
<?= form_error('gender', '<small class="text-danger pl-3">', '</small>'); ?>
</div>
</div>
<div class="form-row">
<div class="col-md-12 mb-4 mt-2">
<label for="">Upload Passport</label>
<input type="file" name="upload_passport[]" id="input-file-now" class="dropify" />
</div>
</div>
this is my model :
public function addGroup()
{
$user = $this->db->get_where('user', ['username' => $this->session->userdata('username')])->row_array();
$pax = $this->getPaxById();
date_default_timezone_set('Asia/Jakarta');
$upload_image = $_FILES['upload_passport[]']['name'];
if ($upload_image) {
$config['upload_path'] = './assets/img/uploads/passport';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
for($i=0;$i<$pax['pax'];$i++) {
if ($this->upload->do_upload('upload_passport[$i]')) {
$new_image = $this->upload->data('file_name');
} else {
echo $this->upload->display_errors();
}
}
}
$name = $this->input->post("name[]");
$gender = $this->input->post("gender[]");
$birthdate = $this->input->post("birthdate[]");
$no_passport = $this->input->post("no_passport[]");
$expire_passport = $this->input->post("expire_passport[]");
$destination = $this->input->post("destination[]");
$date = $this->input->post("date[]");
$dp1 = "0";
$dp2 = "0";
$lunas = "0";
$type = "Group";
$status = "Not Complete";
$permission = "0";
$upload_passport = $new_image;
$upload_dp1 = "default.png";
$upload_dp2 = "default.png";
$date_created = date('d/m/Y H:i:s');
$data = [];
$jumlah = $pax['pax'];
for($x=0;$x<$jumlah;$x++) {
array_push($data, [
'name'=>$this->input->post("name[$x]"),
'id_user'=> $user['id_user'],
'gender'=>$this->input->post("gender[$x]"),
'birthdate'=>$this->input->post("birthdate[$x]"),
'no_passport'=> $this->input->post("no_passport[$x]"),
'expire_passport'=> $this->input->post("expire_passport[$x]"),
'destination'=> $this->input->post("destination[$x]"),
'date'=> $this->input->post("date[$x]"),
'dp1'=> $dp1,
'dp2'=> $dp2,
'lunas'=> $lunas,
'pax'=> $pax['pax'],
'type'=> $type,
'status'=> $status,
'permission'=> $permission,
'upload_passport'=> $new_image,
'upload_dp1'=> $upload_dp1,
'upload_dp2'=> $upload_dp2,
'date_created'=> $date_created
]);
var_dump($data); die;
}
$this->db->insert_batch("passanger", $data);
}
What I want to get is:
array('','','upload_image'), array('','','upload_image')
When insert it to database but when I do it the upload just gets output null and it's not even uploaded to my uploads directory. I would really appreciate it if you help me, I've been stuck on this for 3 days. Thank you.
for ($i=0; $i < sizeof($_FILES['image']['name']) ; $i++) {
$_FILES['file']['name'] = $_FILES['image']['name'][$i];
$_FILES['file']['type'] = $_FILES['image']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['image']['tmp_name'[$i];
$_FILES['file']['error'] = $_FILES['image']['error'][$i];
$_FILES['file']['size'] = $_FILES['image']['size'][$i];
$config['upload_path'] = PRODUCT_IMAGE_UPLOAD_PATH;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if ($this->upload->do_upload('file')){
$images[] = $this->upload->data('file_name');
}else {
echo $this->upload->display_errors();
}
}
Try this in Codeigniter 4
in your controller add this
$image_model = new App\Models\Images(); // Your model name that is load your model
if($imagefiles = $this->request->getFiles())
{
foreach($imagefiles['uploadImages'] as $img)
{
if ($img->isValid() && ! $img->hasMoved())
{
$image_name = $img->getRandomName(); // This is applicable if you want to change the name of the images
if($image_model->save_images($image_name))
{
$img->move(WRITEPATH.'uploads/images/ads', $image_name); // WRITEPATH.'uploads/images/ads' is the part you wish to save you file to
}
}
}
}
In your Model e.g Image model i have a method call save_images()as this
use Codeigniter\Model
class Images extends Model{
public function save_images($image = '')
{
// We set the column 'name' to be allow for data entry into the db. note this is mandatory for now.
// hope it will change in feature. 'name' is the column in database table where you will save the image name
// this command the CI4 db to select only the image column in the database table
$this->allowedFields = ['name'];
return $this->db->table('images')->insert(['name' => $image]);
// echo $sql = $this->db->getLastQuery();
}
}
Then in your html file input, do this
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<input type="file" name="uploadImages[]" multiple>
</div>
</form>
I hope this will work for you

CI set_value not working on get form method

I searched a lot but couldn't find an answer to my problem. The set_value() function is not working on the GET form method whereas it is working on POST. I am trying to get the rows from MySQL and I want to use the GET method for this. Can anyone help, please?
view:
<?=form_open('employee_registration/search_employee', ['role'=>'form','method'=>'GET']);?>
<div class="row">
<div class="col-sm-3">
<div class="form-group">
<label>R. No.<span class="required">*</span></label>
<input class="form-control" placeholder="R. No." name="srch_r_no" id="srch_r_no" value="<?=set_value('srch_r_no');?>">
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
<label>Name<span class="required">*</span></label>
<input class="form-control" placeholder="Name" name="srch_e_name" id="srch_e_name" value="<?=set_value('srch_e_name');?>">
</div>
</div>
</div>
<button type="submit" class="btn btn-primary" name="srch_btn">Search <span class="fa fa-search"></span></button>
<?=form_close();?>
Controller:
public function search_employee()
{
$get = $this->input->get();
unset($get['srch_btn']);
$table = $this->md_emp_reg->search_employee($get);
$this->index('view',$table);
}
model:
public function search_employee($get)
{
$parameters = $this->filter_values($get,"search");
$query = "CALL `sp_select_employee_details`(".$parameters.");";
$grid = $this->table($query);
return $grid;
}
public function filter_values($arr,$type)
{
$arr_keys = array_keys($arr);
$filtered_values = "";
for ($i=0; $i < count($arr); $i++)
{
if ($arr[$arr_keys[$i]] == "" && $type == "search")
{
$arr[$arr_keys[$i]] = "";
}
elseif($arr[$arr_keys[$i]] == "" && $type != "search")
{
$arr[$arr_keys[$i]] = NULL;
}
$filtered_values .= $this->db->escape($arr[$arr_keys[$i]]).",";
}
return rtrim($filtered_values,',');
}
public function table($query)
{
$result = $this->db->query($query);
$r_arr = $result->result_array();
$result_fields_name = $result->list_fields();
$result_num_fields = $result->num_fields();
$result_num_rows = $result->num_rows();
$table = '<table width="100%" class="table table-condensed table-striped table-bordered table-hover" id="dataTables-example"><thead><tr>';
for ($a=0; $a < $result_num_fields; $a++)
{
$table .= "<th>".$result_fields_name[$a]."</th>";
}
$table .="</tr></thead><tbody>";
for ($i=0; $i < count($r_arr) ; $i++)
{
$table .= "<tr>";
for ($j=0; $j < $result_num_fields ; $j++)
{
$table .= "<td>".$r_arr[$i][$result_fields_name[$j]]."</td>";
}
$table .= "</tr>";
}
$table .="</tbody></table>";
$this->db->close();
return $table;
}
Here is the function:
function set_value($field, $default = '', $html_escape = TRUE)
{
$CI =& get_instance();
$value = (isset($CI->form_validation) && is_object($CI->form_validation) && $CI->form_validation->has_rule($field))
? $CI->form_validation->set_value($field, $default)
: $CI->input->post($field, FALSE);
isset($value) OR $value = $default;
return ($html_escape) ? html_escape($value) : $value;
}
Removing the form_validation logic as it isn't useful to us we get:
function set_value($field, $default = '', $html_escape = TRUE)
{
$CI =& get_instance();
$value = $CI->input->post($field, FALSE);
isset($value) OR $value = $default;
return ($html_escape) ? html_escape($value) : $value;
}
Exchanging for post we can create our own helper set_value_get(), save it in a helper, load the helper .etc.:
function set_value_get($field, $default = '', $html_escape = TRUE)
{
$CI =& get_instance();
$value = $CI->input->get($field, FALSE);
isset($value) OR $value = $default;
return ($html_escape) ? html_escape($value) : $value;
}
Usage would be the same as set_value.

CodeIgniter 3 upload image just reloading the page

I am trying to make an upload form but when I submit it, it just refreshes the form, does not even go back to the designated route and no message is shown. Here is my add() function:
public function add()
{
if ($this->input->post()) {
$data['upload_path'] = './uploads/';
$data['allowed_types'] = 'jpg|png|gif';
$data['max_size'] = '500';
$data['max_width'] = '1024';
$data['max_height'] = '768';
$this->load->library('upload', $data);
if ($this->upload->do_upload('imagem')) {
$image_data = $this->upload->data();
$this->session->set_flashdata('message', 'Imagem \'' . $image_data['file_name'] . '\' adicionada');
} else {
$this->session->set_flashdata('message', 'Erro: ' . $this->upload->display_errors());
}
redirect('/admin/banners', 'refresh');
}
$data['page'] = $this->config->item('admin_template_dir_admin') . '/banners/add';
$data['module'] = 'admin';
$this->load->view($this->_container, $data);
}
The form:
<form action="/admin/banners/adicionar" method="POST" enctype="multipart/form-data">
<div class="form-group">
<small>Imagens de até 1024x768</small>
</div>
<div class="form-group">
<label for="selecionar_imagem">Selecionar Imagem</label>
<input type="file" name="imagem" required/>
</div>
<hr/>
<div class="form-group">
<button class="btn btn-primary pull-right">Adicionar</button>
</div>
</form>
Am I missing something?
I made it. It seems I did have to modify the way I was doing the things. I had to create a separated method upload(), instead of doing that if condition inside of the same method I was rendering the view.
public function add()
{
$data['page'] = $this->config->item('admin_template_dir_admin') . '/banners/add';
$data['module'] = 'admin';
$this->load->view($this->_container, $data);
}
public function upload()
{
$this->load->library('upload', array(
'upload_path' => './uploads/',
'allowed_types' => 'jpg',
'max_size' => '5000',
'overwrite' => true
));
if ($this->upload->do_upload('imagem')) {
$this->session->set_flashdata('message', 'Imagem de Banner adicionada');
} else {
$this->session->set_flashdata('message', 'Erro: ' . $this->upload->display_errors());
}
redirect('/admin/banners', 'refresh');
}
And then in the form, modify the method to /admin/banners/upload.

Not displaying error when using upload multi file in codeigniter 2.0

I'm very new in codeigniter. I have a problem when upload multi file in codeigniter.
My upload form can upload multi files, resize and save them to database, everything is Ok, only one thing is not ok : not display error. Example: maximum file is 2MB, i choose file 3MB, it's not display message "The file you are attempting to upload is larger than the permitted size." The same error when i click button upload but not choose a file. The view will display like a image as link. (i'm not enought reputation to post images)
https://drive.google.com/file/d/0B2zpQIbKaLa6Z2Z6LXFrNXlVRUk/view?usp=sharing
This is my Controller:upload.php
private function _upload_files($field='userfile'){
$files = array();
foreach( $_FILES[$field] as $key => $all )
foreach( $all as $i => $val )
$files[$i][$key] = $val;
$files_uploaded = array();
for ($i=0; $i < count($files); $i++) {
$_FILES[$field] = $files[$i];
if ($this->upload->do_upload($field))
$files_uploaded[$i] = $this->upload->data($files);
else
//$files_uploaded[$i] = null;
$files_uploaded[$i] = $this->upload->display_errors();
}
return $files_uploaded;
}
public function do_upload(){
$data['error']="";
$this->_data['loadPage']="upload/upload_view";
$this->load->model('Mcategorie');
$this->_data["categories"] = $this->Mcategorie->listAllCate();
$this->load->model('Malbum');
$this->_data['albums']=$this->Malbum->listAllAlbum1();
$user_folder = './uploads/'.$this->session->userdata('username');
$thumb_folder = './uploads/'.$this->session->userdata('username').'/thumbnail/';
if(!is_dir($user_folder)){
mkdir($user_folder, 0777);
}
if(is_dir($user_folder)){
if(!is_dir($thumb_folder))
mkdir($thumb_folder,0777);
}
if($this->input->post("ok")){
$config['upload_path'] = $user_folder;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '2048';
$config['max_width'] = '';
$config['max_height'] = '';
$config['overwrite'] = FALSE;
$config['remove_spaces'] = TRUE;
$this->load->library("upload",$config);
$this->load->library("image_lib");
if ($_FILES['image_list']) {
$images_upload= $this->_upload_files('image_list');
//echo "<pre>";
//print_r($images_upload);exit;
foreach($images_upload as $data){
$config['image_library'] = 'gd2';
$config['source_image'] = './uploads/'.$this->session->userdata('username').'/'.$data['file_name'];
$config['create_thumb'] = TRUE;
$config['new_image'] = './uploads/'.$this->session->userdata('username').'/thumbnail/'.$data['file_name'];
$config['maintain_ratio'] = FALSE;
$config['width'] = 400;
$config['height'] = 300;
$this->image_lib->initialize($config);
$this->image_lib->resize();
$file = array(
'name' => $data['raw_name'].$data['file_ext'],
'thumb_name' => 'thumb_'.$data['raw_name'].$data['file_ext'],
'date' => date("Y-m-d"),
'userid' => $this->session->userdata('userid'),
'username' => $this->session->userdata('username'),
'description' => $this->input->post("description"),
'roleid' => $this->session->userdata("roleid"),
'public' => $this->input->post("kiet"),
'albumid' => $this->input->post("album"),
'categoryid' => $this->input->post("cat"),
);
$this->Mupload->insert_images($file);
}
redirect(base_url()."default/user/profile","refresh");
}
}
$this->load->view ( $this->_data['path'], $this->_data);
}
This is my view: upload_view.php
<div class="upload container col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div class="panel panel-info">
<div class="panel-heading"><strong>Upload Files</strong> <small>Sao Bac Dau Photo Sharing</small></div>
<div class="panel-body">
<!-- Standar Form -->
<form action="<?php echo base_url()."default/upload/do_upload"?>" method="post" enctype="multipart/form-data">
<div class="col-xs-6 col-sm-6 col-md-6 col-lg-6">
<label> Chọn file ảnh cần upload (jpg, jpeg, gif, png) : </label>
<div class="error col-xs-12 col-sm-12 col-md-12 col-lg-12 clear-css" style="color:#FF0081; font-weight: bold">
<?php if(isset($error)){echo $error; }?>
</div>
<div class="input-group">
<span class="input-group-btn" >
<span class="btn btn-primary btn-file">
Browse … <input type="file" multiple id="image_list" name="image_list[]" accept="image/*" >
</span>
</span>
<input type="text" class="form-control" readonly>
</div>
<input type="submit" name="ok" class="btn btn-md btn-primary" value="Upload Photo" >
</div>
</form>
</div>
</div>
What should i do to display error ? Sorry if my english is so bad. thank in advance for your help.
You will store error in $files_uploaded[$i] = $this->upload->display_errors(); but not use of this to display error so you need to fetch error from this array and display it on view.
Please see below code.
<?php
class Upload extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index()
{
$this->load->view('upload_form', array('error' => ' ' ));
}
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);
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);
}
}
}
?>

Resources