Проблема:
Чтобы установить переменную сеанса и перенаправить пользователя на другую PHP-страницу после загрузки файла.txt с помощью загрузки файла jQuery.
HTML-код (upload.php):
<!-- The fileinput-button span is used to style the file input field as button -->
<span class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span>Add files...</span>
<!-- The file input field used as target for the file upload widget -->
<input id="fileupload" type="file" name="files[]" multiple>
</span>
<br>
<br>
<!-- The global progress bar -->
<div id="progress" class="progress">
<div class="progress-bar progress-bar-success"></div>
</div>
<!-- The container for the uploaded files -->
<div id="files" class="files"></div>
Код jQuery (upload.php):
<script>
$(function () {
'use strict';
// Server-side upload handler:
var url = 'process.php';
$('#fileupload').fileupload({
url: url,
autoUpload: true,
acceptFileTypes: /(\.|\/)(txt)$/i,
maxFileSize: 5000000, // 5 MB
done: function (e, data) {
$(this).delay(2000, function(){
window.location = "explorer.php";
});
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
</script>
PHP upload script (process.php):
<?php
session_start();
$folder = 'upload';
if (!empty($_FILES))
{
// Set temporary name
$tmp = $_FILES['files']['tmp_name'];
// Set target path and file name
$target = $folder . '/' . $_FILES['files']['name'];
// Upload file to target folder
$status = move_uploaded_file($tmp, $target);
if ($status)
{
// Set session with txtfile name
$_SESSION['txtfile'] = $_FILES['files']['name'];
}
}
?>
Желаемый результат:
РЕДАКТИРОВАТЬ: РЕШЕН. Окончательный код выше!
Для начинающих...
Обратите внимание, что ваше имя input
- это files[]
и имеет атрибут multiple
. Это означает, что вы отправляете массив файлов на сервер, чтобы ссылаться на них в php, вам понадобится что-то вроде этого:
$_FILES['files']['name'][0]
для первого файла.
Кроме того, я обнаружил, что move_uploaded_file()
любит полные пути для адресата, попробуйте привязать к $_SERVER['DOCUMENT_ROOT']
.
Чтобы отправить информацию обратно в jQuery, вы хотели бы использовать echo json_encode()
как...
echo json_encode(array(
'status' => $status,
'message' => 'your message here'
));
В вашей done
функции доступ к данным можно получить следующим образом:
done: function(e, data){
console.log(data.status);
console.log(data.message);
}