I want to upload a file from a form. It's working fine with .doc files but .pdf's don't work all the time. I'm not able to load my pdf named compositionFinale.pdf (3.67 MB)
I tried with another big pdf that was more than my $_FILES["size"] and I have an error that tells me:"Ce fichier est trop volumineux" (the file is too big).
But with compositionFinale.pdf that is also too big it doesn't pass in my
if ($_FILES["offre"]["size"] > 500000) (I put a echo to test). I don't have an error at the end and it tells me that the file is uploaded, but when I check in the file it is not.
EDIT: I tried to save this pdf as a reduced size pdf and when I upload my file it tells me that my file is too big. Which is fine. But why does not tell me it is too big when it was not reduced in size?
Is anyone see something I don't?
My controller
function publierOffreEmploi()
{
// validation
$this->form_validation->set_rules('poste', 'Poste', 'required|max_length[255]');
$this->form_validation->set_rules('ville', 'Ville', 'required|max_length[50]');
$this->form_validation->set_rules('description', 'Description', 'required');
$this->form_validation->set_rules('secteurs[]', "Secteur(s) d'activité", 'required');
$this->form_validation->set_rules('date_fin_publication', 'Date de la fin de publication', 'required');
$this->form_validation->set_error_delimiters('<br /><span class="error erreur">', '</span>');
// si erreur dans la validation
if ($this->form_validation->run() == FALSE)
{
$this->_layoutHaut();
$this->load->view('entreprise/formulaire_publier_offre_emploi_view');
$this->_layoutBas();
}
// si aucune erreur dans la validation
else
{
// +++++++++++++++++++++++++++++++++++++++++++
$target_dir = "assets/uploads/";
$name = basename($_FILES["offre"]["name"]);
$target_file = $target_dir . basename($_FILES["offre"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
$message = '';
// Si le formulaire a bien été envoyé
if(isset($_POST["submit"]))
{
// Vérifie si un fichier est bien sélectionné
if(($_FILES['offre']['name'])!= '')
{
$uploadOk = 1;
$pasDeFichier = "";
}
else
{
// définir le message d'erreur de l'image si le fichier choisi n'est pas une image
$uploadOk = 0;
$pasDeFichier = "Vous devez importer un fichier";
}
// si le fichier existe déja
if (file_exists($target_file))
{
// définir le message d'erreur de l'image si l'image existe déja dans le fichier de téléchargement
$uploadOk = 0;
$message.= "Ce fichier exite déja. Veillez le renommer<br>";
}
// si le fichier est plus gros que 500Ko
if ($_FILES["offre"]["size"] > 500000)
{
echo "too big";
die();
$uploadOk = 0;
// définir le message d'erreur si l'image est trop volumineuse
$message.= "Ce fichier est trop volumineux<br>";
}
// définir les formats autorisés
if($imageFileType != "pdf" && $imageFileType != "doc" && $imageFileType != "docx" && $imageFileType != "DOC" && $imageFileType != "DOCX" && $imageFileType != "PDF")
{
// définir le message d'erreur si l'image n'est pas d'un format accepté
$uploadOk = 0;
$message.= "Seuls les fichiers .pdf, .doc et .docx sont acceptés";
}
// si erreur donc pas d'upload et retour au formulaire avec message d'erreur en fonction de l'erreur
if ($uploadOk == 0)
{
if ($pasDeFichier != "") {
$data=array();
$data["message"]= $pasDeFichier;
$this->_layoutHaut();
$this->load->view('entreprise/formulaire_publier_offre_emploi_view', $data);
$this->_layoutBas();
}
else{
$data=array();
$data["message"]= $message;
$this->_layoutHaut();
$this->load->view('entreprise/formulaire_publier_offre_emploi_view', $data);
$this->_layoutBas();
}
}
/*si l'image a été uploadé*/
else
{
if (move_uploaded_file($_FILES["offre"]["tmp_name"], $target_file)){
}
// Création d'une variable contenant le id de l'entreprise connectée
$idEntreprise = $this->entreprise_model->lire('id', $conditions = array('courriel' => $_SESSION["courriel_entreprise"]));
/*Transformer l'objet en tableau. Nous permet de stocker le id*/
$data=array();
$data["idEntreprise"]= $idEntreprise;
foreach ($idEntreprise as $id) {
}
// ------------------------------ CHECKBOX SECTEURS -----------------------------------------
// Récupération et concaténation des valeurs du checkbox multiple (secteurs)
//déclaration de la variable qui contiendra tous les secteurs
$secteurs ='';
//boucle afin d'optenir tous les secteurs
for ($i=0;$i<count($_POST['secteurs']);$i++)
{
//concaténation des champs
$secteurs .= $_POST['secteurs'][$i];
}
// données envoyées au modèle
$form_data = array(
'poste' => set_value('poste'),
'ville' => set_value('ville'),
'description' => set_value('description'),
'date_fin_publication' => set_value('date_fin_publication'),
'entreprise_id' => $id['id'],
'secteur' => $secteurs,
'type_offre_id' => 2,
'statut_offre_id' => 2,
'offre' => $name
);
// insertion dans la bd
// si l'insertion est un succes
if ($this->offre_model->inserer($form_data) == TRUE)
{
redirect('offre_controller/succes_publication_offre_emploi');
}
// si l'insertion est un echec
else
{
redirect('offre_controller/echec_publication_offre');
}
}
}
}
}
My pdf file
My form
<!-- UPLOAD DE L'OFFRE (PDF, DOC, DOCX) -->
<p>
<!-- affichage du message (gestion des messages d'erreurs) -->
<label for="offre" class="labelVisible labelFile">Veuillez importer votre offre d'emploi<span class="required"></span></label>
<?php echo form_error('offre'); ?>
<input id="offre" type="file" name="offre"/>
<br />
<?php
// si un mesasge d'erreur existe
if(isset($message))
{
?>
<span class="erreur"> <?php echo $message; ?></span>
<?php
}
?>
</p>
Thanks
I bet that PHP upload_max_filesize is set as default (2MB) you need to go to php.ini file and search for upload_max_filesize and change that to whatever you need (8MB, 32MB...). Also you need to set post_max_size to same size or higher.
I assume you are on Windows machine, running XAMPP, right click on icon and look for php.ini file open it and do your magic.
Related
I have a middleware like this:
class HasBilling {
public function handle($request, Closure $next) {
$user_profile = UsersProfile::where('user_id', Auth::id())->first();
if (!is_object($user_profile) && !\Auth::user()->hasPermissionTo('soy-agente') && !\Auth::user()->hasPermissionTo('soy-agente_inversor')) {
return redirect()->route('myaccount.facturacion.ver')->with('error', 'No posees datos de facturación. Antes de usar algunas funciones como facturación, publicidad, merkado, tarifas... debes rellenar los datos.');
}
if(is_object($user_profile) && is_null($user_profile->validate)){
return redirect()->route('myaccount.facturacion.ver')->with('error', 'Tus datos de facturación están pendiente de validar');
}
if(is_object($user_profile) && $user_profile->validate == 2){
return redirect()->route('myaccount.facturacion.ver')->with('error', 'Tus datos de facturación han sido rechazados.');
}
if(!is_null(\Auth::user()->activity) && \Auth::user()->activity == "empresa"){
$autorizado = UsersProfileAutorizado::find($user_profile->id);
if(!is_object($autorizado)){
return redirect()->route('myaccount.autorizado.ver')->with('error', 'No posees ningún autorizado. Al ser una empresa, antes de usar algunas funciones como la facturación o la publicidad debes rellenar los datos de autorizado.');
}
if(is_object($autorizado) && is_null($autorizado->validate)){
return redirect()->route('myaccount.autorizado.ver')->with('error', 'Tu autorizado está pendiente de validar.');
}
if(is_object($autorizado) && $autorizado->validate == 2){
return redirect()->route('myaccount.autorizado.ver')->with('error', 'Tu autorizado ha sido rechazado.');
}
}
return $next($request);
}
}
The problem with this is that it checks the first IF, but the others are omitted.
The middleware works because the first if always checks for it, but the rest "ignore" them.
How can i fix that?
You could store the errors in an array, and redirect at the end of the method.
class HasBilling {
public function handle($request, Closure $next) {
$errors = [];
$user_profile = UsersProfile::where('user_id', Auth::id())->first();
if (
!is_object($user_profile)
&& !\Auth::user()->hasPermissionTo('soy-agente')
&& !\Auth::user()->hasPermissionTo('soy-agente_inversor')
) {
$errors[] = 'No posees datos de facturación. Antes de usar algunas funciones como facturación, publicidad, merkado, tarifas... debes rellenar los datos.';
}
if (
is_object($user_profile)
&& is_null($user_profile->validate)
){
$errors[] = 'Tus datos de facturación están pendiente de validar');
}
// Add other checks where you can append $errors array
if (count($errors) > 0) {
return redirect()
->route('myaccount.facturacion.ver')
->with('errors', $errors);
}
return $next($request);
}
}
When reading the errors in the 'myaccount.autorizado.ver route, you have to make sure to read, parse and show the $errors array instead of the single error. For example in a foreach that shows a list of errors.
I hope you're well. I'm trying to display a message with the search value I've done (I have 3 filed for a search : keyword, article type and date).
I have a function inside my Controller :
public function page_liste_resultat_recherche_article(Request $request)
{
$recherche_effectuer = request()->query('rechercher');
$type_article_recherche = request()->query('type_article');
$date_rechercher = request()->query('date');
$article_rechercher = Article::withTrashed()->when($recherche_effectuer, function($query, $recherche_effectuer){
return $query->where('titre', 'like', "%{$recherche_effectuer}%");
})
->when($type_article_recherche, function($query, $type_article_recherche){
return $query->where('type_article_id', 'like', "%{$type_article_recherche}%");
})
->when($date_rechercher, function($query, $date_rechercher){
return $query->where('created_at', 'like', "%{$date_rechercher}%");
})->orderBy('created_at', 'desc')->paginate(5);
if((empty($recherche_effectuer)) && (empty($type_article_recherche)) && ($date_rechercher)){
$message_resultat_recherche = "Résultat pour la date " + ($date_rechercher) + " :";
} elseif((empty($recherche_effectuer)) && (!empty($type_article_recherche)) && (empty($date_rechercher))){
$message_resultat_recherche = "Résultat pour le type d'article " + ($type_article_recherche) + " :";
} elseif((empty($recherche_effectuer)) && (!empty($type_article_recherche)) && (!empty($date_rechercher))){
$message_resultat_recherche = "Résultat pour la date " + ($date_rechercher) + " et le type d'article " + ($type_article_recherche) + " :";
} elseif((!empty($recherche_effectuer)) && (empty($type_article_recherche)) && (empty($date_rechercher))){
$message_resultat_recherche = "Résultat pour le mot cle " + ($recherche_effectuer) + " :";
} elseif((!empty($recherche_effectuer)) && (empty($type_article_recherche)) && (!empty($date_rechercher))){
$message_resultat_recherche = "Résultat pour le(s) mot(s) clé(s) " + ($recherche_effectuer) + " et pour la date " + ($date_rechercher) + " :";
} elseif((!empty($recherche_effectuer)) && (!empty($type_article_recherche)) && (empty($date_rechercher))){
$message_resultat_recherche = "Résultat pour le(s) mot(s) clé(s) " + ($recherche_effectuer) + "et le type d'article " + ($type_article_recherche) + " :";
} elseif((!empty($recherche_effectuer)) && (!empty($type_article_recherche)) && (!empty($date_rechercher))){
$message_resultat_recherche = "Résultat pour le(s) mot(s) clé(s) " +($recherche_effectue) + ", le type d'article " + ($type_article_recherche) + " et la date " + ($date_rechercher) + " :";
} else {
$message_resultat_recherche = "Vous n'avez saisi aucune donnée";
}
return view('admin/article/admin_liste_resultat_recherche', [
'articles' => $article_rechercher,
'resultat' => $message_resultat_recherche
]);
}
Inside my view I show this :
<div class="row d-flex justify-content-center">
<div class="col-md-12">
<p class="text-center mt-3">{{$resultat}}</p>
</div>
</div>
I've this error :
A non-numeric value encountered
Did someone see where I'm wrong please ?
Cordially
Warning: A non-numeric value encountered
As #apokryfos said in a comment, don't concatenate strings with '+' sign. Use '.' instead.
i.e
// Use...
echo "Hello". " world! ". 508;
// Instead of...
echo "Hello"+ " world! "+ 508;
I am using the SAME code that I use on another platform, but the difference is that here I use euros.
I have created a different PayPal account, which is also in euros.
private $_api_context;
public function __construct()
{
//setup PayPal api context
$paypal_conf = \Config::get('paypal');
$this->_api_context = new ApiContext(new OAuthTokenCredential($paypal_conf['client_id'], $paypal_conf['secret']));
$this->_api_context->setConfig($paypal_conf['settings']);
}
public function postPayment()
{
$payer = new Payer();
$payer->setPaymentMethod('paypal');
$items = array();
$subtotal = 0;
$cart = \Session::get('cart');
$currency = 'EUR';
//PEDIDO ACTUAL
$pedidoActual = DB::table('pedido as pe')
->select('pe.subtotal')
->where('pe.idpedido','=',$cart['idpedido'])
->first();
$monto = number_format($pedidoActual->subtotal,2);
$item = new Item();
$item->setName("Pedido de Momento Mágico")
->setCurrency($currency)
->setDescription("Entrega a domicilio incluido")
->setQuantity(1)
->setPrice($monto);
$items[] = $item;
$subtotal = $monto;
///////////////
$item_list = new ItemList();
$item_list->setItems($items);
//Nos sirve si queremos agregar un costo por el envío
$details = new Details();
$subtotal = $subtotal;
$details->setSubtotal($subtotal)
->setShipping(0);
//Es el objeto que tiene la moneda, el detalle a pagar y envio
$amount = new Amount();
$amount->setCurrency($currency)
->setTotal($subtotal)
->setDetails($details);
//Los datos de la transacción
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($item_list)
->setDescription('Pedido de Prueba en App Store');
//Recibe la ruta si se realiza o se cancela el pago
$redirect_urls = new RedirectUrls();
$redirect_urls->setReturnUrl(\URL::route('payment.status'))
->setCancelUrl(\URL::route('payment.status'));
//A traves del objeto Payment creamos el pago
$payment = new Payment();
$payment->setIntent('Sale') //De tipo Venta directa, puede ser de otros tipos
->setPayer($payer)
->setRedirectUrls($redirect_urls)
->setTransactions(array($transaction));
//Enviamos el pago y si hay errores lo mostramos en el Debug
try
{
$payment->create($this->_api_context);
}
catch (\PayPal\Exception\PPConnectionException $ex) {
if (\Config::get('app.debug')) {
echo "Exception: " . $ex->getMessage() . PHP_EOL;
$err_data = json_decode($ex->getData(), true);
exit;
} else {
die('Ups! Algo salió mal');
}
}
// Si todo salió bien, Paypal nos devuelve información
foreach($payment->getLinks() as $link) {
if($link->getRel() == 'approval_url') {
$redirect_url = $link->getHref();
break;
}
}
// add payment ID to session // para darle seguimiento al usuario que lo hizo
\Session::put('paypal_payment_id', $payment->getId());
if(isset($redirect_url)) {
// redirect to paypal
return \Redirect::away($redirect_url);
}
return \Redirect::route('home')
->with('error', 'Ups! Error desconocido.');
}
public function getPaymentStatus(Request $request)
{
// Get the payment ID before session clear
$payment_id = \Session::get('paypal_payment_id');
$cart = \Session::get('cart');
// clear the session payment ID
\Session::forget('paypal_payment_id');
$input = $request->all();
$payerId = Arr::except($input,array('PayerID'));
$token = Arr::except($input,array('token'));
//$payerId = \Input::get('PayerID');
//$token = \Input::get('token');
//if (empty(\Input::get('PayerID')) || empty(\Input::get('token'))) {
if (empty($payerId) || empty($token) || empty($payment_id)) {
$notificarError = (new MailController)->errorPagoPaypal();
return \Redirect::route('home')
->with('message', 'Hubo un problema al intentar pagar con Paypal');
}
//Si se pudo realizar el pago
$payment = Payment::get($payment_id, $this->_api_context);
// PaymentExecution object includes information necessary
// to execute a PayPal account payment.
// The payer_id is added to the request query parameters
// when the user is redirected from paypal back to your site
$execution = new PaymentExecution();
$execution->setPayerId($payerId);
//Execute the payment
$result = $payment->execute($execution, $this->_api_context);
//echo '<pre>';print_r($result);echo '</pre>';exit; // DEBUG RESULT, remove it later
if ($result->getState() == 'approved') { // payment made
// Eliminar carrito
// Enviar correo a user
$fecha_prog_envio = (new CartController)->obtenerFechaEnvio($cart['tipo_producto']);
// Enviar correo a user
$notificarPagoPayPal = (new MailController)->notificarPagoIngresado($fecha_prog_envio,'PayPal');
$this->saveOrder(\Session::get('cart'),$fecha_prog_envio);
\Session::forget('cart');
return \Redirect::route('home')
->with('message', 'Pago realizado correctamente.');
}
return \Redirect::route('home')
->with('message', 'La compra fue cancelada');
}
I have already read all the forums, checked the amounts are correct and it doesn't work.
It is not an authentication issue as I have tried to connect to the other platform and the error is the same.
I imagine that the error may come from the currency exchange, the total amount. But I have not found the error.
$execution->setPayerId($payerId);
What is the value of $payerId at this stage of using it? Log it.
It's supposed to be a plain string value, but your code before this where you set and check payerId looks funny, I don't trust the value.
Problem:
When try to store an image in MySql database field (BLOB) through codeigniter service, the image is not enabled in mysql. (I know is not a good practice but requirement). When is upload the image through mysl admin, image its ok.
How do i test?
I use postman with several text fields and one "file" field where i take the image to be stored in database.
Postman
Results of test:
All "text" fields are stored in database, the "file" field is uploaded to a directory as expected but the bynary data is not stored in database in field "foto"
Results in MySql
Code in Codeigneter:
public function CrearCliente(){
$user = $this->input->post('user');
$nombre = $this->input->post('nombre');
$apellido = $this->input->post('apellido');
$rut = $this->input->post('rut');
$correo = $this->input->post('correo');
$id_pais = $this->input->post('id_pais');
$fecha = $this->input->post('creacion');
$password = $this->input->post('password');
$presentacion = $this->input->post('presentacion');
$telefono = $this->input->post('telefono');
$long = 0;
$lat = 0;
$res="null";
$this->load->library('form_validation');
$mimetypes = array("image/jpeg", "image/pjpeg", "image/gif", "image/png");
$foto = $_FILES['foto']['name'];
$tamanio = $_FILES['foto']["size"];
$archivo = $_FILES['foto']['tmp_name'];
$type = $_FILES['foto']['type'];
$imagen = fopen($archivo, 'rb');
$contenido2 = fread($imagen, $tamanio);
$contenido=file_get_contents($archivo,TRUE);
$contenido3 = $this->db->escape_str($contenido);
fclose($imagen);
if(!in_array($type, $mimetypes))
die("El archivo que subiste no es una imagen válida");
$config['upload_path'] = './imagenes/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '5000000';
$config['quality'] = '90%';
$config['overwrite'] = TRUE;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$config['file_name'] = $foto;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('foto')) {
$error = array('error' => $this->upload->display_errors());
$data['uploadError'] = $this->upload->display_errors();
die('error');
}
else{
$data = array('upload_data' => $this->upload->data());
}
$this->load->model('Usuario');
$res = $this->Usuario->InsertUsuario($contenido3,$user, $nombre, $apellido,$rut, $correo, $foto,$tamanio,$id_pais,$fecha,$password,$presentacion,$telefono,$long,$lat); // *se le asigna una variable al modelo para guardar el contenido que retorna la bd
header('content-type: application/json'); //* se colcoa una cabezera para decir que se va a retornar un Json
echo json_encode($res);
}
function InsertUsuario($contenido,$user, $nombre, $apellido,$rut, $correo, $foto,$tamanio,$id_pais,$fecha,$password,$presentacion,$telefono,$long,$lat)
{
$hoy=getdate();
if ($foto) {
echo $contenido;
}
else{
$imagen = null;
header('content-type: application/json');
echo json_encode("./upload/error.jpg");
}
$this->db->trans_strict(TRUE);
$this->db->trans_start();
$data = array(
'user' => $user,
'nombre' => $nombre,
'apellido' => $apellido,
'id_rut' => $rut,
'correo' => $correo,
'foto' => $contenido,
'id_pais' => $id_pais,
'password' => $password,
'presentacion' => $presentacion,
'telefono' => $telefono,
'creacion' => $fecha,
'long' => $long,
'lat' => $lat
);
$this->db->insert('wm_clientes',$data);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE)
{
return $res='ERROR';
}
else
{
return $res='OK';
}
}
Question: Why the data related to image (jpg) file is not storing in database? Check image. I tried a lot of things but seen to be more difficult i expected. Need help gurus!
strong text
Try this:
public function CrearCliente() {
$user = $this->input->post('user');
$nombre = $this->input->post('nombre');
$apellido = $this->input->post('apellido');
$rut = $this->input->post('rut');
$correo = $this->input->post('correo');
$id_pais = $this->input->post('id_pais');
$fecha = $this->input->post('creacion');
$password = $this->input->post('password');
$presentacion = $this->input->post('presentacion');
$telefono = $this->input->post('telefono');
$long = 0;
$lat = 0;
$res = "null";
$this->load->library('form_validation');
$mimetypes = array("image/jpeg", "image/pjpeg", "image/gif", "image/png");
$foto = $_FILES['foto']['name'];
$tamanio = $_FILES['foto']["size"];
$archivo = $_FILES['foto']['tmp_name'];
$type = $_FILES['foto']['type'];
//$imagen = fopen($archivo, 'rb');
//$contenido2 = fread($imagen, $tamanio);
//fclose($imagen);
if (!in_array($type, $mimetypes)) {
// ci upload checks mimes for you
show_error("El archivo que subiste no es una imagen válida");
}
$config['upload_path'] = './imagenes/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '5000000';
$config['quality'] = '90%';
$config['overwrite'] = TRUE;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$config['file_name'] = $foto;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('foto')) {
//$error = array('error' => $this->upload->display_errors());
//$data['uploadError'] = $this->upload->display_errors();
show_error($this->upload->display_errors());
}
$contenido = file_get_contents($this->upload->data('full_path'));
$contenido3 = $this->db->escape_str($contenido);
$this->load->model('Usuario');
$res = $this->Usuario->InsertUsuario($contenido3, $user, $nombre, $apellido, $rut, $correo, $foto, $tamanio, $id_pais, $fecha, $password, $presentacion, $telefono, $long, $lat); // *se le asigna una variable al modelo para guardar el contenido que retorna la bd
header('content-type: application/json'); //* se colcoa una cabezera para decir que se va a retornar un Json
echo json_encode($res);
}
function InsertUsuario($contenido, $user, $nombre, $apellido, $rut, $correo, $foto, $tamanio, $id_pais, $fecha, $password, $presentacion, $telefono, $long, $lat) {
$hoy = getdate();
if ($foto) {
echo $contenido;
} else {
$imagen = null;
header('content-type: application/json');
echo json_encode("./upload/error.jpg"); // this doesn't seem valid, also you should probably exit
}
// no need for transaction when only running 1 query
$this->db->trans_strict(TRUE);
$this->db->trans_start();
$data = array(
'user' => $user,
'nombre' => $nombre,
'apellido' => $apellido,
'id_rut' => $rut,
'correo' => $correo,
'foto' => $contenido,
'id_pais' => $id_pais,
'password' => $password,
'presentacion' => $presentacion,
'telefono' => $telefono,
'creacion' => $fecha,
'long' => $long,
'lat' => $lat
);
$this->db->insert('wm_clientes', $data);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) {
return $res = 'ERROR';
} else {
return $res = 'OK';
}
}
I would also suggest sending the array of data to the insert function instead of each as a parameter - it is messy and confusing and prone to errors. I also wouldn't suggest mixing string return types with json return types as it is an inconsistent interface. Also if you are using ajax you need to use FormData or a plugin to upload a file in case you weren't.
Any easy way around this would be to just store the image on your server (which you are doing already with your code) and then save the image name to your database as a varchar.
$config['upload_path'] = './imagenes/';
Above is the code that is uploading it to your server. It goes to that path on your server using the upload library provided by codeigniter.
You can now query your database for the image name, rather than the actual image, and use that in your view in an image tag. This will pull the image from the server.
If you have any questions about this method let me know.
I'm trying to upload an image in symfony 3, but when i execute my controller display me this error message "Call to a member function guessExtension() on string ". Before the image was stored in my directory web/uploads/images only and not in my database. And when i try to fix this problem, i have this error.
This is my entity:
namespace Doctix\MedecinBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\File;
/**
* Media
*
* #ORM\Table(name="media")
* #ORM\Entity(repositoryClass="Doctix\MedecinBundle\Repository\MediaRepository")
* #ORM\HasLifecycleCallbacks
*/
class Media
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="url", type="string", length=255)
*/
private $url;
/**
* #var string
*
* #ORM\Column(name="alt", type="string", length=255)
*/
private $alt;
/**
* #ORM\Column(type="string")
*
* #Assert\NotBlank(message="Ajouter une image valide")
* #Assert\File(mimeTypes={ "image/jpeg", "image/png", "image/gif" })
*/
private $image;
// On ajoute cet attribut pour y stocker le nom du fichier temporairement
private $tempFilename;
// On modifie le setter de File, pour prendre en compte l'upload d'un
fichier
lorsqu'il en existe déjà un autre
public function getImage()
{
return $this->image;
}
public function setImage($image)
{
$this->image = $image;
return $this;
// On vérifie si on avait déjà un fichier pour cette entité
if (null !== $this->url) {
// On sauvegarde l'extension du fichier pour le supprimer plus tard
$this->tempFilename = $this->url;
// On réinitialise les valeurs des attributs url et alt
$this->url = null;
$this->alt = null;
}
}
/**
* #ORM\PrePersist()
* #ORM\PreUpdate()
*/
public function preUpload()
{
// Si jamais il n'y a pas de fichier (champ facultatif)
if (null === $this->image) {
return;
}
// Le nom du fichier est son id, on doit juste stocker également son
extension
// Pour faire propre, on devrait renommer cet attribut en « extension »,
plutôt que « url »
$this->url = $this->image->guessExtension(); **Error location**
// Et on génère l'attribut alt de la balise <img>, à la valeur du nom du
fichier sur le PC de l'internaute
$this->alt = $this->image->getClientOriginalName();
}
/**
* #ORM\PostPersist()
* #ORM\PostUpdate()
*/
public function upload()
{
// Si jamais il n'y a pas de fichier (champ facultatif)
if (null === $this->image) {
return;
}
// Si on avait un ancien fichier, on le supprime
if (null !== $this->tempFilename) {
$oldFile = $this->getUploadRootDir().'/'.$this->id.'.'.$this-
>tempFilename;
if (file_exists($oldFile)) {
unlink($oldFile);
}
}
// On déplace le fichier envoyé dans le répertoire de notre choix
$this->image->move(
$this->getUploadRootDir(), // Le répertoire de destination
$this->id.'.'.$this->url // Le nom du fichier à créer, ici « id.extension
»
);
}
/**
* #ORM\PreRemove()
*/
public function preRemoveUpload(){
// On sauvegarde temporairement le nom du fichier, car il dépend de l'id
$this->tempFilename = $this->getUploadRootDir().'/'.$this->id.'.'.$this->url;
}
/**
* #ORM\PostRemove()
*/
public function removeUpload(){
// En PostRemove, on n'a pas accès à l'id, on utilise notre nom sauvegardé
if (file_exists($this->tempFilename)) {
// On supprime le fichier
unlink($this->tempFilename);
}
}
public function getUploadDir(){
// On retourne le chemin relatif vers l'image pour un navigateur
return 'uploads/images';
}
protected function getUploadRootDir(){
// On retourne le chemin relatif vers l'image pour notre code PHP
return __DIR__.'/../../../../web/'.$this->getUploadDir();
}
public function getWebPath(){
return $this->getUploadDir().'/'.$this->getId().'.'.$this->getUrl();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set url
*
* #param string $url
*
* #return Media
*/
public function setUrl($url)
{
$this->url = $url;
return $this;
}
/**
* Get url
*
* #return string
*/
public function getUrl()
{
return $this->url;
}
/**
* Set alt
*
* #param string $alt
*
* #return Media
*/
public function setAlt($alt)
{
$this->alt = $alt;
return $this;
}
/**
* Get alt
*
* #return string
*/
public function getAlt()
{
return $this->alt;
}
}
Then my controller:
public function mediaEditAction(Request $request){
$media = new Media();
$form = $this->createForm(MediaType::class, $media);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$file = $media->getImage();
$fileName = md5(uniqid()).'.'.$file->guessExtension();
$file->move(
$this->getParameter('images_directory'),
$fileName
);
$media->setImage($fileName);
$em = $this->getDoctrine()->getManager();
$em->persist($media);
$em->flush();
$request->getSession()->getFlashBag()->add('Notice', 'Photo ajoutée
avec succès');
// redirection
$url = $this->generateUrl('medecin_parametre');
// redirection permanente avec le status http 301 ::)))))
return $this->redirect($url,301);
}else{
return $this-
>render('DoctixMedecinBundle:Medecin:mediaedit.html.twig', array(
'form' => $form->createView()
));
}
}
Thanks.
Тhe image property of your entity is a string, so it is normal to get the error.
If you want to use guess extension you can use like following:
use Symfony\Component\HttpFoundation\File\File;
$file = new File($this->getUploadRootDir() . '/' . $this->image);
$this->url = $file->guessExtension();