I have this little problem with downloading my xlsx-file.
I am sending my request for the file over jquery Ajax and on the backend the data is correctly collected and assembled to a xlsx-file. So now on its way back to the frontend i am setting all the headers in preparation to force download the file, but the download never starts.
These are the response headers of my request:
Connection Keep-Alive
Content-Disposition attachment; filename="export.xlsx"
Content-Length 346420
Content-Type application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Date Mon, 23 Nov 2015 13:23:30 GMT
Keep-Alive timeout=5, max=91
Server Apache/2.4.16 (Win32) OpenSSL/1.0.1p PHP/5.6.12
Set-Cookie <cookiesettings>
content-transfer-encoding binary
x-powered-by PHP/5.6.12
imho the download should start immediately, but nothing happens.
EDIT:
Until now I used a form submit, but the data amount is really big so the time which is needed to assemble the file is also really long and sometimes a couple of minutes or even an hour, so this was no longer possible.
So I built a java-job to build the file and startet an ajax snippet which asks for completion every second or so.
So here is my Code.
Frontend:
This is called on button-click
download: function (type, maximum) {
var
self = this,
oParams = this.oTable.oApi._fnAjaxParameters(this.oTable.fnSettings()),
aoPost = [
{ 'name': 'exportType', 'value': type },
{ 'name': 'exportMax', 'value': maximum },
{ 'name': 'handleId', 'value': self.options.handleId }
],
nIFrame, nContentWindow, nForm, nInput, i
;
// Call a self made function to get extra search parameters
// without call an data update AJAX call.
self.oTable.fnSettings().addAdditionalSearchData(oParams);
// Create an IFrame to do the request
nIFrame = document.createElement('iframe');
nIFrame.setAttribute('id', 'RemotingIFrame');
nIFrame.style.border = '0px';
nIFrame.style.width = '0px';
nIFrame.style.height = '0px';
document.body.appendChild(nIFrame);
nContentWindow = nIFrame.contentWindow;
nContentWindow.document.open();
nContentWindow.document.close();
nForm = nContentWindow.document.createElement('form');
nForm.className = 'export-table';
nForm.setAttribute('method', 'post');
// Add POST data.
var formData = {};
for (i = 0; i < aoPost.length; i++) {
nInput = nContentWindow.document.createElement('input');
nInput.setAttribute('name', aoPost[ i ].name);
nInput.setAttribute('type', 'text');
nInput.value = aoPost[ i ].value;
nForm.appendChild(nInput);
formData[aoPost[ i ].name] = aoPost[ i ].value;
}
// Add dataTables POST.
for (i = 0; i < oParams.length; i++) {
nInput = nContentWindow.document.createElement('input');
nInput.setAttribute('name', oParams[ i ].name);
nInput.setAttribute('type', 'text');
nInput.value = oParams[ i ].value;
nForm.appendChild(nInput);
formData[oParams[ i ].name] = oParams[ i ].value;
}
nForm.setAttribute('action', '/service/exportTableData');
// Add the form and the iFrame.
nContentWindow.document.body.appendChild(nForm);
// Send the request.
//nForm.submit();
// Send the request.
var form = $(nContentWindow.document.body).find('form.export-table');
var jobId = 0;
form.ajaxForm(
{
'showMessagesOnSuccess': false
},
{
'getData': function () {
return formData;
}
}
).data('ajaxForm').submit();
}
The Ajax request on submit:
$.ajax({
type: 'POST',
url: self.handler.getServiceUrl(),
timeout: GLOBALS.AJAX_REQUEST_TIMEOUT,
cache: false,
data: (<get the Data>)
,
success: function (response) {
if (response.success === true) {
// Check if we have to wait for a result.
if (response.jobId !== undefined && response.jobId !== 0) {
self.checkJobStatus(response.jobId);
} else {
<success - show some messages>
}
} else {
self.handler.error(response);
}
},
error: function () {
<Show error Message>
}
});
The CheckJobStatus:
checkJobStatus: function (jobId) {
var self = this;
$.ajax({
type: 'POST',
timeout: GLOBALS.AJAX_REQUEST_TIMEOUT,
cache: false,
data: { 'jobId': jobId },
url: self.handler.getServiceUrl(),
success: function (response) {
if(response !== null && response.data !== undefined) {
if (response.data.isFinished === true) {
if (response.success === true) {
// Check if we have to wait for a result.
self.handler.success(response);
} else {
self.handler.error(response);
}
} else if (response.success === true && response.data !== null) {
setTimeout(
function () {
self.checkJobStatus(jobId);
},
500
);
} else {
Helper.logFrontendError();
}
} else if (response !== null && response.success === true) {
setTimeout(
function () {
self.checkJobStatus(jobId);
},
1000
);
} else {
Helper.logFrontendError();
}
},
error: function (response) {
Helper.logFrontendError();
}
});
}
Backend - php:
(...)
if ($action == 'exportTableData' || $action == 'exportChartData') {
$responseData = $service->execute();
if(isset($responseData->data['contentType']) && $responseData->data['contentType'] != null && isset($responseData->data['data'])) {
$this->sendTextData($responseData->data['contentType'], $responseData->data['data']);
} else {
$this->sendJsonData($responseData);
}
} else {
$this->sendJsonData($service->execute());
}
(...)
private function sendTextData($contentType, $data) {
$this->set('filename', 'export.xlsx');
$this->set('data', $data);
$this->response->type($contentType);
$this->render('/Layouts/excel', 'excel');
}
(...)
$handlerResult = new HandlerResult();
if($dataServiceResult == null) {
$service = new DataService();
$dataServiceResult = $service->exportTableData(
$controller->Auth->User('id'),
json_encode($request->data),
null
);
} else {
if ($dataServiceResult->header->resultKey == 0) {
$handlerResult->wsData['data'] = $dataServiceResult->data;
$handlerResult->wsData['contentType'] = $dataServiceResult->contentType;
}
}
$handlerResult->wsResultHeader = $dataServiceResult->header;
return $handlerResult; // ++++ this result returns to the first codeblock in this section ++++
Backend - java - This is where the File is assembled:
(...)
if (jobId > 0) {
FrontendJobStatus status = FrontendJobQueue.getJobStatus(context.userId, jobId);
this.result = (WSExportTableDataResult) status.getResult();
logger.info((this.result.data == null) ? "ByteArray is EMPTY" : "ByteArray is NOT EMPTY");
} else {
this.jobId = FrontendJobQueue.addJob(this.context.userId, new ExportTableDataJob(this.context, this.postData));
this.result.header.jobId = this.jobId;
}
(...)
The Jop:
<Workbook assembly>
ByteArrayOutputStream out = new ByteArrayOutputStream();
wb.write(out);
this.result.data = out.toByteArray();
this.result.contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
// this.result.contentType = "application/vnd.ms-excel";
this.result.setResultHeader(APIConstants.RESULT_SUCCESS);
Layout/excel:
<?php
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Content-Transfer-Encoding: binary');
ob_clean();
echo $data;
EDIT 2:
So I tried to open a new window on success with the Data, and i could start the download, but the file ist no valid xlsx File anymore.
var reader = new FileReader();
var blob = new Blob([response.responseText], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
reader.readAsDataURL(blob);
reader.onloadend = function (e) {
window.open(reader.result, 'Excel', 'width=20,height=10,toolbar=0,menubar=0,scrollbars=no', '_blank');
}
Any Ideas?
After a lot of research i found this site and the essence of its statment is that jquery ajax does not support receiving binary data, but provides a solution for implementing plain xhr request which support blob transfer.
The Site:
http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/
To expand on my comment, instead of trying to send back binary data via ajax, simply save to a temp file , send the file reference back to js. On receiving the file reference, simply set window.location.href to point to a filereading endpoint, passing the file reference. I have done this a few times and it works fine even on ancient browsers:
$('#start').click(function(){
$.post('/createfile.php', {some:data}, function(response){
if(response.started){
pollFile(response.fileId);
}
});
);
function pollFile(fileId){
$.get('/filestatus.php?fileid=' + fileId, function(response){
if(response.fileCompleted){
window.location.href = '/downloadfile.php?fileid=' + fileId;
}else{
setTimeout('pollFile', 5000, fileId);
}
});
}
//createfile.php
$fileId = uniqid();
SomePersistentStorage::addJob($fileID);
//start file job here, code should run in a seperate process/thread, so
//either use a job queue system, use shell_exec or make an http request,
//then once job is queued/started:
header('Content-Type: application/json');
echo json_encode(['started'=>true, 'fileId'=>$fileId]);
//processjob.php - the file that does the work, could be your java
//program for example, just using php here for consistency
//after file is done
file_put_contents($filepath, $data);
SomePersistentStorage::updateJob($fileID, true);
//filestatus.php
$fileId = $_GET['fileid'];
header('Content-Type: application/json');
echo json_encode(['fileCompleted'=>SomePersistentStorage::isJobCompleted($fileID)]);
//downloadfile.php
$fileId = $_GET['fileid'];
$filepath = 'tmp/' . $fileId . '.tmp';
//correct headers here, then
readfile($filepath);
unlink($filepath);
If you dont want to imediatly delete the file, then you could just run a cron to delete files in the specific folder, that are older than x.
Related
I m trying to upload a file and a thumb of that file (using the cropper v2.3.0).
This code work on all other browser but in safari it gives an error.
The problem describe as follow:
on safari browser on desktop when upload the file then the below error occurred and used other then safari browser there is no error and get success message.
I test both ways that first upload only the cropped image that is in base64
encode or also in blob as file with appending into formData but on both ways that error not resolved.
I also tried to upload the image only then error occurred sometimes or sometimes not.
if use cropper adjust then the error occurred (this is my assumption)
My js Code to submit the form
function addFile() {
$("#result").html("");
var myForm = $('#mainForm');
var formData = new FormData(myForm[0]);
$.ajax({
url: "action.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: formData, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
dataType: "json",
success: function (data) // A function to be called if request succeeds
{
$("#result").html(data.response + " : " + data.message);
},
error: function (res) {
$("#result").html(res.responseText);
}
});
return false;
}
my action php code
<?php
$uploadThumbnailPath = "dir";
$thumbImgData = $_POST['thumbImg'];
$numberOfImages = 1;
$isImageUploaded = 0;
if ($thumbImgData != "") {
//thumbnail image uploading code
list($type, $thumbImgData) = explode(';', $thumbImgData);
list(, $thumbImgData) = explode(',', $thumbImgData);
$thumbImgData = base64_decode($thumbImgData);
$myTimeStamp = "thumbImg_" . time() . uniqid();
$displayImageName = $myTimeStamp . ".png";
$dir = $uploadThumbnailPath;
if (file_put_contents("$dir/$displayImageName", $thumbImgData)) {
$jpgFormatImageName = $myTimeStamp . ".jpg";
convertPNGtoJPG("$dir/$displayImageName", "$dir/$jpgFormatImageName", 238, 238, 238, 1);
if (file_exists("$dir/$displayImageName")) {
unlink("$dir/$displayImageName");
}
$isImageUploaded = 1;
}
} else {
$arrayResponse = array("response" => "thumbImg_BLANK", "message" => 'thumbImg_BLANK');
echo json_encode($arrayResponse);
exit;
}
for ($i = 1; $i <= $numberOfImages; $i++) {
if (isset($_POST["imgName$i"])) {
$itemImagesName = "";
} else {
$itemImagesName = $_FILES["imgName$i"]['name'];
}
if ($itemImagesName != "") {
$extension = pathinfo($itemImagesName, PATHINFO_EXTENSION);
$uploadNewFileNameWithoutExt = "image_" . md5($i . time());
$uploadDirPath = "dir/p/";
$uploadNewFileName[$i] = $uploadNewFileNameWithoutExt . '.' . $extension;
$uploadNewFileWithPathName = $uploadDirPath . $uploadNewFileName[$i];
$mesUpload = uploadImageFileOnServer("imgName$i", $allowedExts, $maxFileSize, $uploadNewFileWithPathName);
}
}
$itemImages = implode("#:#", $uploadNewFileName);
$thumbnailImageName = "default_thumbnail.png";
if ($isImageUploaded == 1) {
$thumbnailImageName = $jpgFormatImageName;
}
if ($mesUpload == "FILE_UPLOADED") {
$arrayResponse = array("response" => "OK", "message" => "OK UPLOAD SUCCESS");
echo json_encode($arrayResponse);
exit;
} else {
/* $mesUpload */
$arrayResponse = array("response" => "FILE_FAILED", "message" => "FAIL TO UPLOAD");
echo json_encode($arrayResponse);
exit;
}
?>
Here the screen shots of the error of that
this is image where the
screen shot 1
screen shot 2
Please help me to solving this issue. i am puzzled for this error and i have not getting any idea to resolved this problem.
If any one want to use i upload a sample code on the web click on below link
https://tamapev.000webhostapp.com/upload-img/
The issue is probbaly you sending the form data to the wrong page, first determine whether action.php is in the root directory or if it is in a directory called "upload-img". Then send the request to that given page.
Next for the error that says "An error occurred trying to load resource", to see what the actual error is, in your first screenshot there is a little button in the panel that says "Response", Click on it and change it to "JSON"
If "action.php" is in "upload-img" then you need to change
url: "action.php", to url: "/upload-img/action.php",
I'm able to get the file uploaded and in to the directory I want so that part seems to work but I'm not sure why I'm getting a parse error in the js console in chrome. Because of this error my bottom javascript won't execute and I need it to do so.
Here's the ajax:
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
// Grab the files and set them to our variable
function prepareUpload(event)
{
files = event.target.files;
}
$('form').on('submit', uploadFiles);
// Catch the form submit and upload the files
function uploadFiles(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// START A LOADING SPINNER HERE
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
$.ajax({
url: 'submit.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
alert(data);
script = $(data).text();
$.globalEval(script);
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}
Here's the html:
<?php
echo '<span class="new_profile_save_upload_image_span"><img src="'.$url_root.'/images/615721406-612x612.jpg"/ class="new_profile_save_upload_image_img"></span>';
?>
<form action="" method="post" enctype="multipart/form-data" name="new_profile_save_upload_image_input_form" id="new_profile_save_upload_image_input_form">
<input type="file" id="new_profile_save_upload_image_input" name="new_profile_save_upload_image_input" multiple="" accept="image/x-png,image/gif,image/jpeg"/>
<input type="submit" value="Upload Image" name="submit">
</form>
And here is the php:
<?php
// get mysqli db connection string
$mysqli = new mysqli("localhost", "psych_admin", "asd123", "psych");
if($mysqli->connect_error){
exit('Error db');
}
// Get theme settings and theme colours and assign the theme colour to the
theme name
$stmt = $mysqli->prepare("SELECT name FROM user_profiles WHERE rowid=(SELECT
MAX(rowid) FROM user_profiles);");
$stmt->execute();
$result = $stmt->get_result();
while($row_1 = $result->fetch_assoc())
{
$arr_1[] = $row_1;
}
foreach($arr_1 as $arrs_1)
{
$username = $arrs_1['name'];
}
$data = array();
if(isset($_GET['files']))
{
$error = false;
$files = array();
// Make dir for file uploads to be held
if (!file_exists(''.dirname(__FILE__) . '/content/profiles/'.$username.'/avatar'))
{
mkdir(''.dirname(__FILE__) . '/content/profiles/'.$username.'/avatar', 0777, true);
}
$uploaddir = './content/profiles/'.$username.'/avatar/';
foreach($_FILES as $file)
{
if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
{
$files[] = $uploaddir .$file['name'];
}
else
{
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
$data = array('success' => 'Form was submitted', 'formData' => $_POST);
}
echo json_encode($data);
?>
<script>
var scope1 = '<?php echo $url_root;?>';
var scope2 = '<?php echo $username;?>';
var scope3 = '<?php echo $file['name'];?>';
var new_profile_save_upload_image_span_data = '<img src="' + scope1 + '/content/profiles/' + scope2 + '/avatar/' + scope3 + '" class="new_profile_save_upload_image_img">';
$('.new_profile_save_upload_image_span').empty();
$('.new_profile_save_upload_image_span').append(new_profile_save_upload_image_span_data);
</script>
alert(data) doesn't seem to be popping up, so there's something wrong previous to that execution.
I tried this code with simply 'submit.php' but it doesn't seem to work without the 'files' addition to it.
Also do I have the filename correct? Should the file's filename be $file['name'] in php? I'm trying to get the file name as a string and place it in when the default image is (as an image to be displayed), using an img html tag and inserting it via jquery, as you can see at the bottom under .
The ajax should execute this script at the bottom but it doesn't due to the error.
Also is there a nicer way of writing the bottom jquery scripts that I have written?
Error I'm getting:
ERRORS: Syntax Error: Unexpected Token < in JSON at position 103
Thanks in advance.
If you want to return JSON and HTML at the same time, you could put the HTML into an element of the $data array.
<?php
// get mysqli db connection string
$mysqli = new mysqli("localhost", "psych_admin", "asd123", "psych");
if($mysqli->connect_error){
exit('Error db');
}
// Get theme settings and theme colours and assign the theme colour to the
theme name
$stmt = $mysqli->prepare("SELECT name FROM user_profiles WHERE rowid=(SELECT
MAX(rowid) FROM user_profiles);");
$stmt->execute();
$result = $stmt->get_result();
while($row_1 = $result->fetch_assoc())
{
$arr_1[] = $row_1;
}
foreach($arr_1 as $arrs_1)
{
$username = $arrs_1['name'];
}
$data = array();
if(isset($_GET['files']))
{
$error = false;
$files = array();
// Make dir for file uploads to be held
if (!file_exists(''.dirname(__FILE__) . '/content/profiles/'.$username.'/avatar'))
{
mkdir(''.dirname(__FILE__) . '/content/profiles/'.$username.'/avatar', 0777, true);
}
$uploaddir = './content/profiles/'.$username.'/avatar/';
foreach($_FILES as $file)
{
if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
{
$files[] = $uploaddir .$file['name'];
}
else
{
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
$data = array('success' => 'Form was submitted', 'formData' => $_POST);
$data['html'] = <<<EOS
<script>
var scope1 = '$url_root';
var scope2 = '$username';
var scope3 = '{$file['name']}';
var new_profile_save_upload_image_span_data = '<img src="' + scope1 + '/content/profiles/' + scope2 + '/avatar/' + scope3 + '" class="new_profile_save_upload_image_img">';
\$('.new_profile_save_upload_image_span').empty();
\$('.new_profile_save_upload_image_span').append(new_profile_save_upload_image_span_data);
</script>
EOS;
}
echo json_encode($data);
?>
Then in the JavaScript you do:
script = $(data.html).text();
It's better to use try-catch block in your PHP code, and send status with the response set to true or false. Also, send the $url_root and $username variables within the JSON object.
See this beginner's guide on Image Uploading with PHP and AJAX to learn everything about creating AJAX handler, validating, saving and sending a response back to the client side.
I'm using a system curl command via php to download a file. That is all working fine, but I'm now trying to show some progress as it's downloaded.
The curl command and php called is:
$a = popen("cd user; curl -O -# remote.server.com/filename.tar.gz 2>&1", 'r');
ob_flush();flush();
while($b = fgets($a, 64)) {
ob_flush();flush();
if (preg_match('~\b(error|fail|unknown)\b~i',$b)) {
echo "error^$b";
exit;
}
echo str_replace('#','',$b);
ob_flush();flush();
}
pclose($a);
This is called using ajax and the output is displayed in a div:
var last_response_len = false;
$.ajax(url, {
xhrFields: {
onprogress: function(e)
{
var this_response, response = e.currentTarget.response;
if(last_response_len === false)
{
this_response = response;
last_response_len = response.length;
}
else
{
this_response = response.substring(last_response_len);
last_response_len = response.length;
}
$(upg).show();
console.log(this_response)
var count = this_response.match(/%/g);
if (count !== null && count.length != 2) $(msg).html(this_response);
}
}
})
This works but the results showin in the msg div are not consistent.
I may get :
1%
5%
12.1%
12.5% 13.2%
14.2%
5.3%
16.7%
I get partial results ie: 5.3% instead of 15.3%, I get multiple results within the same output ie: 12.5% & 13.2%
is there anyway to standardise this so I only get 0% through to 100% ?
Thanks
change the php str_replace to
str_replace(['#', ' '], '', $b);
Then you get only the percentage, without the preceding blanks, which you can just insert to the container without editing.
Example:
https://3v4l.org/OGWqU
Trying to create a small notification system. When user fills out the profile then his verification status is set to 1 in database and then I would like to show a notification once that "hey you are now verified". Been searching a lot on the internet, but nothing has helped me to reach my goal. If the status is 1 in database I get the Event: verification_ok in the test.php but if it is 0 I get Maximum execution time of 120 seconds exceeded. Also I don't see any response in my client side code.
This is the server side code (test.php).
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header("Connection: Keep-alive");
require_once $_SERVER['DOCUMENT_ROOT'].'/PHP/scripts/no_session_redirect.php';
$key = true;
$ver = $user_home->runQuery("SELECT verification_status FROM verification WHERE user_id=:user_id");
$ver->execute(array(":user_id"=>$user_id));
$status = $ver->fetch(PDO::FETCH_ASSOC);
while($key){
if($status["verification_status"] == 1){
pushNotification($status["verification_status"]);
$key = false;
}else{
$status["verification_status"];
sleep(10);
}
}
function pushNotification() {
echo "Event: verification_ok\n";
}
And here is the client side code:
$(document).ready(function() {
if (typeof(EventSource) !== "undefined") {
// Yes! Server-sent events support!
var source = new EventSource("test.php");
source.addEventListener("verification_ok", function(e) {
console.log(e.data);
}, false);
source.addEventListener("open", function(e) {
}, false);
source.addEventListener("error", function(e) {
if (e.readyState == EventSource.CLOSED) {
console.log("Error - connection was lost.");
}
}, false);
} else {
// Sorry! No server-sent events support..
}
});
I am selecting a file and sending it through XMLXttpRequest like this :
var upload_form = $('#upload_form'),
file_input = $('#file_input'),
file_list = $('#file_list'),
submit_btn = $('#submit_btn'),
uploaders = [];
file_input.on('change', onFilesSelected);
upload_form.on('submit', onFormSubmit);
/**
* Loops through the selected files, displays their file name and size
* in the file list, and enables the submit button for uploading.
*/
function onFilesSelected(e) {
var files = e.target.files,
file,
list_item,
uploader;
for (var i = 0; i < files.length; i++) {
file = files[i];
uploader = new ChunkedUploader(file);
uploaders.push(uploader);
list_item = $('<li>' + file.name + '(' + file.size.formatBytes() + ') <button>Pause</button></li>').data('uploader', uploader);
file_list.append(list_item);
}
file_list.show();
submit_btn.attr('disabled', false);
}
so for each file that I add, I create a new ChunkedUploader object, which chunks the file in little 1MB files.
The code for the ChunkedUploader object is as follows:
function ChunkedUploader(file, options) {
if (!this instanceof ChunkedUploader) {
return new ChunkedUploader(file, options);
}
this.file = file;
this.options = $.extend({
url: 'index/upload'
}, options);
this.file_size = this.file.size;
this.chunk_size = (1024 * 100); // 100KB
this.range_start = 0;
this.range_end = this.chunk_size;
if ('mozSlice' in this.file) {
this.slice_method = 'mozSlice';
}
else if ('webkitSlice' in this.file) {
this.slice_method = 'webkitSlice';
}
else {
this.slice_method = 'slice';
}
this.upload_request = new XMLHttpRequest();
this.upload_request.onload = this._onChunkComplete();
}
_upload: function() {
var self = this,
chunk;
// Slight timeout needed here (File read / AJAX readystate conflict?)
setTimeout(function() {
// Prevent range overflow
if (self.range_end > self.file_size) {
self.range_end = self.file_size;
}
chunk = self.file[self.slice_method](self.range_start, self.range_end);
self.upload_request.open('POST', self.options.url, true);
self.upload_request.overrideMimeType('application/octet-stream');
if (self.range_start !== 0) {
self.upload_request.setRequestHeader('Content-Range', 'bytes ' + self.range_start + '-' + self.range_end + '/' + self.file_size);
}
self.upload_request.send(chunk);
}, 200);
},
It all works okay, but on the PHP end I receive nothing through :$_GET,$_POST or $_FILE. I can see in Firebug that raw data is being sent through post, there are some gibberish data being sent, I presume it's the small chunk that I just cropped from the original file. I have looked everywhere and I can't find anything releated to this case.
Can you point out what I am doing wrong, because I have to no clue.
You may want to file_get_contents('php://input') instead: this is the raw request body, whereas $_POST is already a parsed representation.
See http://php.net/manual/en/wrappers.php.php#wrappers.php.input