1

Tengo un formulario el cual manda cuantos archivos pongas a una carpeta local. Está funcionando solamente en local, pero es cuestión de cambiar de rutas, nada mas.

index.php Página principal, solamente tiene la variable de sesión para controlar errores mediante el php

<?php
    if (isset($_SESSION['message']) && $_SESSION['message'])
    {
      printf('<b>%s</b>', $_SESSION['message']);
      unset($_SESSION['message']);
    }
?>

  <form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php">
    <input type="file" name="file1" id="file1" onchange="uploadFile()" multiple size="50"><br>
    <h3 id="status"></h3>
    <p id="loaded_n_total"></p>
    <input type="submit" id="btn-progressbar" value="Upload" style="visibility:hidden">
  </form>

<template id="temp_prog">
  <div id="demo">
    <h3 class="txt_file_num">  </h3>
    <p class="txt_file_name"></p>
    <p class="txt_file_size"></p>
    <progress class="progressBar" value="0" max="100""></progress>
  </div>
</template>

JS Ya está hecho, pero a la hora de mandar las cosas por el PHP, si es demasiado grande, casca error

let ary = [];

function _(el) {
  return document.getElementById(el);
}

function uploadFile() {
  let file = _("file1");

  if('files' in file){
    if(file.files.length == 0){
      console.log("Select one or more files");

    } else {
      for(let i=0;i < file.files.length;i++){
        //request y declaracion iterada de files
        let ajax = new XMLHttpRequest();
        let x = file.files[i];

        //despliegue del temp
        let txt = createElement();
        document.body.append(txt);

        //push en array
        ary.push(x);

        //logs
        if ('name' in x) {
          txt.getElementsByClassName('txt_file_name')[0].innerHTML = 'Name: '+x.name;
        }
        if ('size' in x) {
          txt.getElementsByClassName('txt_file_size')[0].innerHTML = 'Size: '+x.size;
        }

        let bar = txt.getElementsByClassName('progressBar')[0];

        let formdata = new FormData();
        formdata.append("file1", x);
        ajax.upload.addEventListener("progress",(event)=>{progressHandler(event, bar)}, false);
        ajax.addEventListener("load", completeHandler, false);
        ajax.addEventListener("error", errorHandler, false);
        ajax.addEventListener("abort", abortHandler, false);
        ajax.open("POST", "upload.php"); 
        ajax.send(formdata);

      }
    }
  }
}

function progressHandler(event, bar) {

  _("loaded_n_total").innerHTML = "Uploaded " + event.loaded + " bytes of " + event.total;
  let percent = (event.loaded / event.total) * 100;

  bar.value = Math.round(percent);

  _("status").innerHTML = Math.round(percent) + "% uploaded... please wait";

}

function completeHandler(event) {
  ary.shift();
  console.log('completado');

  if(ary.length == 0){
    //_('btn-progressbar').click();
  }
}

function errorHandler(event) {
  _("status").innerHTML = "Upload Failed";
}

function abortHandler(event) {
  _("status").innerHTML = "Upload Aborted";
}

function createElement(){
  let dv = document.createElement('div');
      dv.setAttribute('class', 'demo');
  let p1 = document.createElement('p');
      p1.setAttribute('class', 'txt_file_name');
  let p2 = document.createElement('p');
      p2.setAttribute('class', 'txt_file_size');
  let pr = document.createElement('progress');
      pr.setAttribute('class', 'progressBar');
      pr.setAttribute('value', '0');
      pr.setAttribute('max', '100');

      dv.append(p1);
      dv.append(p2);
      dv.append(pr);

  return dv;
}

upload.php *El origen de la discordia. *

<?php
session_start();

$message = ''; 
    
  if (isset($_FILES['file1']) /*&& $_FILES['file1']['error'] === UPLOAD_ERR_OK*/){

    // detalles del archivo
    $fileTmpPath = $_FILES['file1']['tmp_name'];
    $fileName = $_FILES['file1']['name'];
    $fileSize = $_FILES['file1']['size'];
    $fileType = $_FILES['file1']['type'];
    $fileNameCmps = explode(".", $fileName);
    $fileExtension = strtolower(end($fileNameCmps));

    $chunk_size = 5120;
    $upload_start = 0;

    // verificador de extensiones
    $allowedfileExtensions = array('jpg', 'gif', 'png', 'zip', 'txt', 'xls', 'doc', 'pdf', '7z', 'mp4', 'img', 'php', 'iso');

    if (in_array($fileExtension, $allowedfileExtensions)){
      // directory in which the uploaded file will be moved
      $uploadFileDir = 'archivos_aaron_pruebas/';
      $dest_path = $uploadFileDir . $fileName;

      if($fileSize < $chunk_size){//Comprueba si tiene mas de 5MB
        
        $handle = fopen($fileTmpPath, "rb");
        $fp = fopen($uploadFileDir, "w");

        $contents = fread($handle, $chunk_size);
        die($contents);
        fwrite($fp, $contents);
        $upload_start += strlen($contents);
        fseek($handle, $upload_start);

        fclose($handle);
        fclose($fp);

        $message = 'Archivo desfragmentado y reacoplado correctamente.';

      } else {
        if(move_uploaded_file($fileTmpPath, $dest_path)){//Mueve archivo al directorio
          $message ='Archivo subido correctamente.';
        } else {
          $message = 'Error al subir el archivo.';
        }
      }
    } else {
      $message = 'Upload failed.';
    }
  } else {
    $message = 'Hubo un error al comprobar variables.';
  }
$_SESSION['message'] = $message;
header("Location: image-loader.php");
/*
<?php
session_start();

$message = ''; 

  if (isset($_FILES['file1']) /*&& $_FILES['file1']['error'] === UPLOAD_ERR_OK)
  {

    // get details of the uploaded file
    $fileTmpPath = $_FILES['file1']['tmp_name'];
    $fileName = $_FILES['file1']['name'];
    $fileSize = $_FILES['file1']['size'];
    $fileType = $_FILES['file1']['type'];
    $fileNameCmps = explode(".", $fileName);
    $fileExtension = strtolower(end($fileNameCmps));

    // sanitize file-name
    $newFileName = md5(time() . $fileName) . '.' . $fileExtension;

    // check if file has one of the following extensions
    $allowedfileExtensions = array('jpg', 'gif', 'png', 'zip', 'txt', 'xls', 'doc', 'pdf', '7z', 'mp4', 'img');

    echo $fileTmpPath; die;

    if (in_array($fileExtension, $allowedfileExtensions))
    {
      // directory in which the uploaded file will be moved
      $uploadFileDir = 'archivos_aaron_pruebas/';
      $dest_path = $uploadFileDir . $newFileName;

      if(move_uploaded_file($fileTmpPath, $dest_path)) 
      {
        $message ='File is successfully uploaded.';
      }
      else 
      {
        $message = 'There was some error moving the file to upload directory. Please make sure the upload directory is writable by web server.';
      }
    }
    else
    {
      $message = 'Upload failed. Allowed file types: ' . implode(',', $allowedfileExtensions);
    }
  }
  else
  {
    $message = 'There is some error in the file upload. Please check the following error.<br>';
    $message .= 'Error:' . $_FILES['file1']['error'];
  }
$_SESSION['message'] = $message;
header("Location: image-loader.php");
?>

He intentado hacer un "chunk uploader" en el que fragmento el archivo en pequeños trozos de 5MB, ya que si mando algo con más de 5MB al formulario, casca.

He seguido un tutorial que hacen esta jugada:

if($fileSize < $chunk_size){//Comprueba si tiene mas de 5MB
        
        $handle = fopen($fileTmpPath, "rb");
        $fp = fopen($uploadFileDir, "w");

        $contents = fread($handle, $chunk_size);
        die($contents);
        fwrite($fp, $contents);
        $upload_start += strlen($contents);
        fseek($handle, $upload_start);

        fclose($handle);
        fclose($fp);

        $message = 'Archivo desfragmentado y reacoplado correctamente.';

      }

Pero se la salta a la torera. Me gustaría saber cómo poder fragmentar el archivo en pequeños trozos y subirlos poco a poco.

1
  • Debes realizar modificaciones tanto en Javascript para enviar por partes y en PHP para recibir cada parte y, solo hasta que se hayan subido todas, unirlas para guardar en un solo archivo.
    – Triby
    Commented el 21 may. 2021 a las 15:13

1 respuesta 1

0

El bucle ya está correctamente controlado:

var chunk, txt, start, part, BYTES_PER_CHUNK, end;

function selectFile(){
    let file = _("file1");

    if('files' in file){
        for(let i=0;i < file.files.length;i++){
            let x = file.files[i];
            start = 0;
            part = 0;
            BYTES_PER_CHUNK = 1048576;

            //despliegue del temp
            txt = createElement();
            document.body.append(txt);

            //logs
            if ('name' in x) {
                txt.getElementsByClassName('txt_file_name')[0].innerHTML = '<strong>Name:</strong> '+x.name;
            }
            if ('size' in x) {
                txt.getElementsByClassName('txt_file_size')[0].innerHTML = '<strong>Size:</strong> '+x.size;
            }            

            uploadComplete(x);
        }
    }
}

function uploadFile(chunkFile, part, x){
    let xhr = new XMLHttpRequest();
    let bar = txt.getElementsByClassName('progressBar')[0];
    xhr.upload.addEventListener("progress",(event)=>{uploadProgress(event, bar, x)}, false);
    xhr.addEventListener("error", uploadFailed, false);
    xhr.addEventListener("abort", uploadCanceled, false);
    xhr.open("POST", "upload.php"+"?"+"file="+x.name+"&num=" + part);
    xhr.setRequestHeader('Cache-Control','no-cache');
    let fd = new FormData();
    fd.append("file1", chunkFile);
    xhr.send(fd);
    return;
}

function uploadComplete(x) {
    let pol =[];
    start = 0;
    end = BYTES_PER_CHUNK;
    part = 0;
    while( start < x.size ) {
        chunk = x.slice(start, end);
        console.log(start);
        uploadFile(chunk, part, x);
        start = end;
        end = start + BYTES_PER_CHUNK;
        part++;
        pol.push({part:part,start:start,end:end});
    }
    console.log(pol);
}

function uploadProgress(event, bar, x) {
    //let total_size = x.size;
    let slice = parseInt(x.size/(1024*1024));
    


    _("loaded_n_total").innerHTML = "Uploaded " + event.loaded + " bytes of " + event.total;
    let percent = (event.loaded / event.total) * 100;
    bar.value = Math.round(percent);
    _("status").innerHTML = Math.round(percent) + "% uploaded... please wait";
}

function uploadFailed(event) {
    _("status").innerHTML = "Upload failed";
}
  
function uploadCanceled(event) {
    _("status").innerHTML = "Upload canceled";
}

function createElement(){
    let dv = document.createElement('div');
        dv.setAttribute('class', 'demo');
    let p1 = document.createElement('p');
        p1.setAttribute('class', 'txt_file_name');
    let p2 = document.createElement('p');
        p2.setAttribute('class', 'txt_file_size');
    let pr = document.createElement('progress');
        pr.setAttribute('class', 'progressBar');
        pr.setAttribute('value', '0');
        pr.setAttribute('max', '100');
  
        dv.append(p1);
        dv.append(p2);
        dv.append(pr);
  
    return dv;
  }

function _(el) {
    return document.getElementById(el);
  }

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.