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.