PHP Ajax 업로드 진행률 표시줄
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input name="uploaded" type="file" />
<input type="submit" value="Upload" />
</form>
<?php
if(isset($_REQUEST['submit'])){
$target = "data/".basename( $_FILES['uploaded']['name']) ;
move_uploaded_file($_FILES['uploaded']['tmp_name'], $target);
}
?>
저는 Javascript, AJAX, JQuery 등을 잘 알고 있으며 PHP, AJAX, Javascript 등을 사용하여 업로드 진행 표시줄을 만들 수 있다고 생각합니다.
업로드 진행 중 업로드 크기(1초당 알고 싶은 크기, 업로드된 파일의 양과 남아있는 양, AJAX 등)를 어떻게 얻을 수 있는지 놀랍습니다.
여기 PHP 설명서 링크가 있지만 이해하지 못했습니다: http://php.net/manual/en/session.upload-progress.php
PHP와 AJAX를 사용하지만 PHP의 외부 확장을 사용하지 않고 업로드 진행률 표시줄을 표시하는 다른 방법이 있습니까?에 액세스할 수 없습니다.php.ini
소개
PHP 문서는 매우 상세합니다.
업로드가 진행 중이고 session.upload_progress.name INI 설정과 동일한 이름의 변수를 POST할 때 $_SESSION superglobal에서 업로드 진행률을 사용할 수 있습니다.PHP가 이러한 POST 요청을 감지하면 $_SESSION에 배열을 채웁니다. 여기서 인덱스는 session.upload_progress.prefix 및 session.upload_progress.name INI 옵션의 연결된 값입니다.키는 일반적으로 이러한 INI 설정을 읽음으로써 검색됩니다.
당신이 필요로 하는 모든 정보는 PHP 세션 명명에 준비되어 있습니다.
- start_time
- 내용_길이
- bytes_beta
- 파일 정보(복수 지원)
이 정보를 추출하여 HTML 양식으로 표시하기만 하면 됩니다.
기본 예제
a.1987년
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
var intval = null;
var percentage = 0 ;
function startMonitor() {
$.getJSON('b.php',
function (data) {
if (data) {
percentage = Math.round((data.bytes_processed / data.content_length) * 100);
$("#progressbar").progressbar({value: percentage});
$('#progress-txt').html('Uploading ' + percentage + '%');
}
if(!data || percentage == 100){
$('#progress-txt').html('Complete');
stopInterval();
}
});
}
function startInterval() {
if (intval == null) {
intval = window.setInterval(function () {startMonitor()}, 200)
} else {
stopInterval()
}
}
function stopInterval() {
if (intval != null) {
window.clearInterval(intval)
intval = null;
$("#progressbar").hide();
$('#progress-txt').html('Complete');
}
}
startInterval();
</script>
b.1987년
session_start();
header('Content-type: application/json');
echo json_encode($_SESSION["upload_progress_upload"]);
PHP 세션 업로드 진행률 예제
다음은 PHP 세션 업로드 진행률의 최적화된 버전입니다.
자바스크립트
$('#fileupload').bind('fileuploadsend', function (e, data) {
// This feature is only useful for browsers which rely on the iframe transport:
if (data.dataType.substr(0, 6) === 'iframe') {
// Set PHP's session.upload_progress.name value:
var progressObj = {
name: 'PHP_SESSION_UPLOAD_PROGRESS',
value: (new Date()).getTime() // pseudo unique ID
};
data.formData.push(progressObj);
// Start the progress polling:
data.context.data('interval', setInterval(function () {
$.get('progress.php', $.param([progressObj]), function (result) {
// Trigger a fileupload progress event,
// using the result as progress data:
e = document.createEvent('Event');
e.initEvent('progress', false, true);
$.extend(e, result);
$('#fileupload').data('fileupload')._onProgress(e, data);
}, 'json');
}, 1000)); // poll every second
}
}).bind('fileuploadalways', function (e, data) {
clearInterval(data.context.data('interval'));
});
진행 상황
$s = $_SESSION['upload_progress_'.intval($_GET['PHP_SESSION_UPLOAD_PROGRESS'])];
$progress = array(
'lengthComputable' => true,
'loaded' => $s['bytes_processed'],
'total' => $s['content_length']
);
echo json_encode($progress);
기타 예제
이것은 내 코드입니다. 정상적으로 작동합니다. 시도해 보세요:
데모 URL (끊긴 링크)
http://codesolution.in/dev/jQuery/file_upload_with_progressbar/
아래 코드를 사용해 보십시오.
HTML:
<!doctype html>
<head>
<title>File Upload Progress Demo #1</title>
<style>
body { padding: 30px }
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }
.progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
.bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
.percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
</head>
<body>
<h1>File Upload Progress Demo #1</h1>
<code><input type="file" name="myfile"></code>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploadedfile"><br>
<input type="submit" value="Upload File to Server">
</form>
<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<div id="status"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
bar.width("100%");
percent.html("100%");
status.html(xhr.responseText);
}
});
})();
</script>
</body>
</html>
upload.php:
<?php
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
?>
FileDrop을 제안합니다.
프로그레스바를 만들 때 사용했는데, 꽤 쉽습니다.
제가 만난 유일한 단점은 많은 양의 데이터로 작업하는 데 문제가 있다는 것입니다. 오래된 파일을 정리하지 못하는 것 같기 때문입니다. 수동으로 수정할 수 있습니다.
JQuery로 쓰이지는 않았지만 어쨌든 꽤 괜찮은 편이고, 작가는 질문에 꽤 빨리 대답합니다.
진행률 표시줄에 대한 코드를 작성하는 것이 재미있을 수도 있지만, 기존 구현을 선택하는 것은 어떻습니까?Andrew Valums는 훌륭한 작품을 썼고 여기에서 찾을 수 있습니다.
저는 그것을 제 모든 프로젝트에 사용하고 그것은 매력적으로 작동합니다.
우선, 당신의 컴퓨터에 PHP 5.4가 설치되어 있는지 확인하세요.당신은 php-5.4를 태그하지 않아서 잘 모르겠습니다.호출로 확인echo phpversion();(또는)php -v명령행에서).
이 있다고 하면, 어든버, 올바을가가있정당다, 에서 정확한 할 수 .php.ini파일. 당신이 그렇게 할 수 없다고 하니, 제가 어떻게 하는지 설명할 가치가 없습니다.
대체 솔루션으로 플래시 개체 업로더를 사용합니다.
XMLHTTPREQUSET2
var xhr = new XMLHttpRequest();
xhr.open('GET', 'video.avi', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
var blob = this.response;
/*
var img = document.createElement('img');
img.onload = function(e) {
window.URL.revokeObjectURL(img.src); // Clean up after yourself.
};
img.src = window.URL.createObjectURL(blob);
document.body.appendChild(img);
/*...*/
}
};
xhr.addEventListener("progress", updateProgress, false);
xhr.send();
function updateProgress (oEvent) {
if (oEvent.lengthComputable) {
var percentComplete = oEvent.loaded / oEvent.total;
console.log(percentComplete)
} else {
// Unable to compute progress information since the total size is unknown
}
}
언급URL : https://stackoverflow.com/questions/9878161/php-ajax-upload-progress-bar
'codememo' 카테고리의 다른 글
| 보기에 ID를 프로그래밍 방식으로 할당하려면 어떻게 해야 합니까? (0) | 2023.08.01 |
|---|---|
| Swift를 사용하여 iOS에서 SMS 보내기 (0) | 2023.08.01 |
| builder @angular-devkit/build-angular:dev-server on server 명령에 대한 구현을 찾을 수 없습니다. (0) | 2023.07.27 |
| 서비스 계정을 변경하는 Powershell 스크립트 (0) | 2023.07.27 |
| 중첩 종속성을 "yarn"으로 재정의하려면 어떻게 해야 합니까? (0) | 2023.07.27 |