И вроде задача простая. Но вот уже мозг кипит и не могу понять что не так.
Сначала вроде работало в Яндекс.Браузере, но стал пробывать в Safari и не работает и понеслась.
В общем форма отправки, гляньте свежим взглядом:
<div class="card rounded-0 shadow col-lg-5 col-md-7 col-sm-12 mx-auto">
<div class="card-body">
<div class="container-fluid">
<form action="" id="sample-form">
<div class="mb-3 d-none" id="progress-holder">
<div class="progress">
<div class="progress-bar" id="progress_bar" role="progressbar" aria-label="Example with label" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0%</div>
</div>
</div>
<div class="mb-3">
<label for="formFile" class="form-label">Выбирите ZIP-архив</label>
<input class="form-control" type="file" accept="image/*, video/*, .zip" name="upload" id="formFile" required />
</div>
</form>
</div>
<table class="table table-striped table-bordered">
<colgroup>
<col width="20%">
<col width="80%">
</colgroup>
<thead>
<tr class="bg-primary text-light">
<th class="text-center">№</th>
<th class="text-center">Имя файла</th>
</tr>
</thead>
<tbody>
<?php
$dir = "temp/";
if(is_dir($dir)):
$scandr = scandir($dir);
$i = 1;
foreach($scandr as $file):
if(in_array($file, ['.', '..']))
continue;
?>
<tr>
<th class="text-center"><?= $i++ ?></th>
<td><a href="<?= $dir.$file ?>" target="_blank"><?= $file ?></a></td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
</div>
</div>
Файл скрипта app.js:
$(document).ready(function(){
$('#formFile').change(function(){
var inpFile = $(this).clone();
var newForm = new FormData();
newForm.append('uploaded', inpFile[0].files[0]);
$('#progress-holder').removeClass('d-none');
var progressBar = $('#progress_bar');
progressBar.text('0%');
progressBar.attr('aria-valuenow',0);
progressBar.css('width',0);
$.ajax({
url:"upload.php",
data:newForm,
method:'POST',
type:"POST",
headers: {
'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundaryQUWQnB6c7TzNzdcz'
},
async: true,
cache: false,
processData:false,
contentType:false,
dataType:'json',
error: function(xhr, textStatus, error) {
console.log(xhr.responseText);
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
},
xhr: function(){
var xhr = $.ajaxSettings.xhr();
xhr.upload.addEventListener('progress', function(e){
if(e.lengthComputable){
var completed = e.loaded/e.total;
var perc = Math.floor(completed * 100);
console.log("Upload:", perc);
progressBar.text(perc+'%');
progressBar.attr('aria-valuenow',perc);
progressBar.css('width',perc+'%');
}
}, false);
xhr.addEventListener('progress', function(e){
if(e.lengthComputable){
var completed = e.loaded/e.total;
var perc = Math.floor(completed * 100);
console.log("Download:",perc);
progressBar.text(perc+'%');
progressBar.attr('aria-valuenow',perc);
progressBar.css('width',perc+'%');
}
}, false);
return xhr;
},
success:function(response){
var MyInterval = setInterval(function(){
console.log("progress now:", progressBar.attr('aria-valuenow'));
if(progressBar.attr('aria-valuenow') == 100){
if(response.status == 'success'){
console.log("Uploaded Filename:", response.filename);
alert("File has been uploaded successfully");
}else{
alert(response.error);
}
clearInterval(MyInterval);
location.reload();
}
},1000);
}
});
});
});
И принимающий PHP (upload.php):
<?php
@ini_set( 'upload_max_size', '528MB' );
// ini_set( 'post_max_size', '528MB' );
// ini_set( 'memory_limit', '528MB' );
$dir = "./temp/";
if(!is_dir($dir)){
mkdir($dir, 0777 );
}
$log = date('Y-m-d H:i:s') . ' ' . print_r($_FILES, true) . "\n=>" . $_FILES['uploaded']['name'] . "\n=>" . PHP_EOL . ob_get_clean() . PHP_EOL;
file_put_contents( './log.txt', $log . PHP_EOL, FILE_APPEND);
if(isset($_FILES['uploaded']) && !empty($_FILES['uploaded']['tmp_name'])){
$fname = $_FILES['uploaded']['name'];
$i = 0;
while(true){
$tmp_name = $dir . ($i > 0 ? $i . "_" :'') . $fname;
if(is_file($tmp_name)){
$i++;
}else{
$fname = $tmp_name;
break;
}
}
$upload = move_uploaded_file($_FILES['uploaded']['tmp_name'], $fname);
if( $upload ){
echo json_encode(['status' => 'success', 'filename' => $fname]);
} else {
echo json_encode(['status' => 'failed', 'error' => "failed to upload"]);
}
} else {
echo json_encode(['status' => 'fUCK!!!', 'error' => "FUCK!!!"]);
}