Advertisement
Guest User

Rota PHP e Ajax

a guest
Jul 17th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.85 KB | None | 0 0
  1. //Ajax
  2. $.ajax({
  3.                 url:'/admin/upload/image',
  4.                 method: 'POST',
  5.                 data: form,                
  6.                 contentType: false,
  7.                 processData: false,
  8.                 //Pegando o recurso de progresso nativo do JQUERY para o javascript
  9.                 xhr: function(){
  10.                     const xhr = $.ajaxSettings.xhr();
  11.                     xhr.upload.addEventListener('progress', function (e){
  12.                         //calculando a porcentagem
  13.                         let progress = e.loaded / e.total * 100;
  14.                         //Passando a porcentagem carregada
  15.                         attachment.setUploadProgress(progress);
  16.                     });
  17.                     return xhr;
  18.                 }
  19.             }).done(function(resp){
  20.                         //console.log('resp');
  21.                         console.log(resp);
  22.  
  23.  
  24. //PHP
  25. elseif(resolve('/admin/upload/image')){    
  26.     $file = !empty($_FILES['file'])? $_FILES['file'] : NULL;
  27.     if(!$file){
  28.          (422);
  29.         //echo json_encode(['status' => 'Nenhum arquivo enviado']);
  30.         echo 'Nenhum arquivo enviado';
  31.         exit;
  32.     }
  33.     $allowedType =[
  34.         'image/gif',  
  35.         'image/jpg',
  36.         'image/jpeg',
  37.         'image/png',
  38.     ];
  39.     //Se não estiver nos tipos permitidos
  40.     if(!in_array($file['type'], $allowedType)){
  41.         http_response_code(422);        
  42.         echo 'Arquivo não permitido, utilize arquivos: gif, jpg, jpeg ou png';
  43.         exit;
  44.     }
  45.    
  46.     //Criando um nome randomico para o arquivo
  47.     $name = uniqid(rand(), true) . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
  48.    
  49.     //Movendo a imagem para o diretorio no servidor
  50.     move_uploaded_file($file['tmp_name'], __DIR__.'/../public/upload/'. $name);
  51.    
  52.     //print_r($file);
  53.     echo '/upload/'. $name;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement