В php я пишу код для загрузки файла с помощью chunck. это работает на локальном сервере. но в режиме реального времени сервер не загружает более 13 МБ, файл прерывается. В то же время размер сообщения сервера, время выполнения увеличивается, но он все еще прерывается во время отправки вызова ajax.
нижняя страница является HTML-страницей
<script>
function upload(fileInputId, fileIndex) {
// take the file from the input
//document.getElementById('art_frm').method = 'PUT';
$.browser.safari = ($.browser.webkit && !(/chrome/.test(navigator.userAgent.toLowerCase())));
if ($.browser.safari) {
var safari = 1;
}else{
var safari = -1;
}
var ms_ie = false;
var ua = window.navigator.userAgent;
var old_ie = ua.indexOf('MSIE ');
var new_ie = ua.indexOf('Trident/');
var file = document.getElementById(fileInputId).files[fileIndex];
var reader = new FileReader();
var fileName = file.name;
var rand_num = Math.floor((Math.random() * 100000000000000) + 1);
var type = getExtension(file.name);
var id = document.getElementById('id')!=null ? document.getElementById('id').value : '';
var folder = '';
fileName = rand_num+fileName.replace(/[^a-z0-9\s\.]/gi, '').replace(/[_\s]/g, '-');
$("#randomName").val(fileName);
// reading file
if (typeof(reader.readAsBinaryString) == 'undefined') {
reader.readAsDataURL(file); // alternatively you can use readAsDataURL
} else {
reader.readAsBinaryString(file); // alternatively you can use readAsDataURL
}
reader.onloadend = function(evt) {
// create XHR instance
xhr = new XMLHttpRequest();
// send the file through POST
if(id){
var params = 'action=uploadfile&file-name='+fileName+'&id='+id;
var url = '/upload-picture.php';
}
else{
var params = 'action=uploadfile&file-name='+fileName;
var url = '/upload-picture.php';
}
if ((old_ie > -1) || (new_ie > -1)) {
url = url + '?browser=IE';
}else{
url = url + '?browser=NOT-IE';
}
setTimeout(function() { xhr.abort(); alert("ajax call timeout!") },40000000);
xhr.open("POST",url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader("X-File-Name", fileName);
// make sure we have the sendAsBinary method on all browser
XMLHttpRequest.prototype.mySendAsBinary = function(text){
var data = new ArrayBuffer(text.length);
var ui8a = new Uint8Array(data, 0);
for (var i = 0; i < text.length; i++) {
ui8a[i] = (text.charCodeAt(i) & 0xff);
}
//blob code
try{
var blob = new Blob( [data]);
}
catch(e){
// TypeError old chrome and FF
window.BlobBuilder = window.BlobBuilder
|| window.WebKitBlobBuilder
|| window.MozBlobBuilder
|| window.MSBlobBuilder;
if(e.name == 'TypeError' && window.BlobBuilder){
var bb = new BlobBuilder();
bb.append([data.buffer]);
var blob = bb.getBlob();
}
else if(e.name == "InvalidStateError"){
// InvalidStateError FF13 WinXP
var blob = new Blob( [data.buffer]);
}
else{
// We're screwed, blob constructor unsupported entirely
}
}
//end blob
this.send(blob);
}
// let's track upload progress
var eventSource = xhr.upload || xhr;
eventSource.addEventListener("progress", function(e) {
// get percentage of how much of the current file has been sent
var position = e.position || e.loaded;
var total = e.totalSize || e.total;
var percentage = Math.round((position/total)*100);
var myBar = document.getElementById('progress-bar');
var divBar = document.getElementById('bar'+fileIndex);
var str_disp = '';
var str_color = '';
if(divBar!=null) {
if(position >= file.size) {
str_disp = 'Loading..';
str_color = '#4679BD';
} else {
str_disp = percentage+"%";
str_color = '#9DC3FF';
}
divBar.innerHTML = "<label> </label><font style='color:"+str_color+";background:#fff;'><div style='width:270px;float:left;text-align:center;position:relative;margin:0 0 10px;float:left;'><span style='position:absolute;left:0;top:0px;width:100%;text-align:center;'> </span><span style='background:"+str_color+";display:block;height:5px;border:1px solid #9DC3FF;width:"+percentage+"%'> </span>"+str_disp+"</div></font>";
} else {
myBar.innerHTML = myBar.innerHTML+"<div id='bar"+fileIndex+"'></div>";
}
//document.getElementById("profile_pic").disabled = true;
document.getElementById('progress').innerHTML = '';
// here you should write your own code how you wish to proces this
});
// state change observer - we need to know when and if the file was successfully uploaded
console.log(xhr);
xhr.onreadystatechange = function() {
console.log(xhr.readyState,xhr.responseText);
if(xhr.readyState == 4) {
if(xhr.status == 200) {
// process success\
if(xhr.responseText == '') {
alert("file is not uploaded");
return false;
} else {
document.getElementById("progress-bar").innerHTML='uploaded!';
}
} else {
}
}
};
// start sending
xhr.mySendAsBinary(evt.target.result);
};
}
function getFiles(){
var imageFiles = document.getElementById("profile_pic");
var i = 0
var myBar = document.getElementById('progress-bar');
myBar.innerHTML = myBar.innerHTML+"<label> </label><div id='bar"+i+"' style='float:left;'><font style='color:#9DC3FF'>"+imageFiles.files[i].name+" uploading..<br/></font><div style='width:270px;border:1px solid #9DC3FF;text-align:center;position:relative;margin:0 0 10px;'><span style='position:absolute;left:0;top:0px;width:100%;text-align:center;'> </span><span style='background:#9DC3FF;display:block;height:5px;width:2%'> </span></div></div>";
upload('profile_pic',i);
}
</script>
<body>
</body>
Ударная страница — это php-страница upload-picture.php
<?php
define("ARTS_PIC_TEMP_THUMBNAIL_PATH","uploads/");
$uploaded_file_name = $_SERVER['HTTP_X_FILE_NAME'];
$opt = uploadingArts($uploaded_file_name);
function uploadingArts($filename=''){
//$filename=($filename);
$path_of = ARTS_PIC_TEMP_THUMBNAIL_PATH.$filename;
$dest_dir = ARTS_PIC_TEMP_THUMBNAIL_PATH;
$brwName = getBrowser();
if($brwName=='Internet Explorer'){
//for IE
$content = file_get_contents('php://input'); //the string we get contains 2 parts
$content = str_replace(' ','+',$content); // we need to replace spaces by plusses
$content = split(",",$content); // we do not need the first part of the string (the one with the file type).
$content = base64_decode($content[1]);
file_put_contents($dest_dir.''.$filename, $content);
return true;
}
else { //other than IE
// read contents from the input stream
$inputHandler = fopen('php://input', "r");
$fileHandler = fopen($path_of, "w+");
// save data from the input stream
while(true) {
//4096
$buffer = fgets($inputHandler, 1096);
if (strlen($buffer) == 0) {
fclose($inputHandler);
fclose($fileHandler);
return true;
}
fwrite($fileHandler, $buffer);
}
}
}
?>
после вызова ajax вызов файла upload-picture.php прерывается через некоторое время только на живом сервере.
Что я должен сделать для загрузки загружать большие файлы, такие как файлы 38,39 МБ?
Задача ещё не решена.
Других решений пока нет …