PHP Image Upload Not Resizing When Sent Via JS - javascript

I am running into issues when uploading an image sent to PHP via JS. I can upload the image fine, but I would to resize the image before moving it to it's new destination. I can also rename the image without any issues. It's really just the resizing that is the issue here.
After a lot of searching I have seen a lot of questions regarding this on SO, which is how I got to where I am now, but not one that answers this 100%. If you know of a question/answer already on SO please link me to the correct article.
Any help is much appreciated, thanks.
Here is the JS
var test = document.querySelector('#afile');
test.addEventListener('change', function() {
var file = this.files[0];
var fd = new FormData();
fd.append('afile', file);
// These extra params aren't necessary but show that you can include other data.
fd.append('id', burgerId);
var xhr = new XMLHttpRequest();
// why wont this work in the actions directory?
xhr.open('POST', 'actions/upload.php', true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded / e.total) * 100;
var uploadProcess = document.getElementById('uploadProcess');
uploadProcess.setAttribute('style', 'width: ' + percentComplete + '%;');
// uploadProcess.innerHTML = parseInt(percentComplete) + '% uploaded';
}
};
xhr.onload = function() {
if (this.status == 200) {
var resp = JSON.parse(this.response);
image = 'img/' + resp.newFileName;
sessionStorage.setItem('burgerLoc', image);
var image = document.createElement('img');
image.src = resp.dataUrl;
document.body.appendChild(image);
};
};
xhr.send(fd);
// upImage(id)
}, false);
Here is the markup
<input type="file" name="afile" id="afile" accept="image/*"/>
Here is the PHP
$image = $_FILES['afile']['name'];
$image_tmp = $_FILES['afile']['tmp_name'];
$image_type = $_FILES['afile']['type'];
function getName($str) {
$parts = explode('.',$str);
$imgName = str_replace(' ', '_',$parts[0]);
return $imgName;
}
function getExtension($str) {
$parts = explode('.',$str);
$ext = $parts[1];
return $ext;
}
$image_name = stripslashes($image);
$name = getName($image_name);
$image_ext = getExtension($image_name);
$ext = strtolower($image_ext);
if($ext == 'jpg' || $ext == 'jpeg' ) {
$ext = 'jpg';
$src = imagecreatefromjpeg($image_tmp);
} else if($ext == 'png') {
$src = imagecreatefrompng($image_tmp);
} else {
$src = imagecreatefromgif($image_tmp);
}
$file_content = file_get_contents($image_tmp);
$data_url = 'data:' . $image_type . ';base64,' . base64_encode($file_content);
list($width,$height) = getimagesize($image_tmp);
// width of the main image
$new_width = 748;
$new_height = ($height / $width) * $new_width;
$img_dest = imagecreatetruecolor($new_width,$new_height);
imagecopyresampled($img_dest,$src,0,0,0,0,$new_width,$new_height,$width,$height);
// rename the file
$new_file_name = strtolower($_REQUEST['id'] . '.' . $ext);
$new_file_location = '../img/' . $new_file_name;
imagejpeg($img_dest,$new_file_name,100);
move_uploaded_file($image_tmp, $new_file_location);
imagedestroy($src);
imagedestroy($img_dest);
$json = json_encode(array(
'dataUrl' => $data_url,
'extension' => $ext,
'id' => $_REQUEST['id'],
'name' => $image,
'newFileName' => $new_file_name,
'type' => $image_type
));
echo $json;

I would maybe try installing ImageMagick in your linux distribution and try to use this function to resize the image
http://php.net/manual/en/imagick.resizeimage.php
I have reproduced your script on my webserver... I have made modifications and came up with this.
The most significant modification is that I am using exact paths in the file locations, and that I am moving the tmp file to a real file, load that real file, resize that real file instead of trying it to do with the tmp uploaded file.
PHP:
<?php
$image = $_FILES['afile']['name'];
$image_tmp = $_FILES['afile']['tmp_name'];
$image_type = $_FILES['afile']['type'];
function getName($str) {
$parts = explode('.',$str);
$imgName = str_replace(' ', '_',$parts[0]);
return $imgName;
}
function getExtension($str) {
$parts = explode('.',$str);
$ext = $parts[1];
return $ext;
}
$image_name = stripslashes($image);
$name = getName($image_name);
$image_ext = getExtension($image_name);
$ext = strtolower($image_ext);
$outputfolder = "/var/www/html/wp-content/";
$new_file_name = strtolower($_REQUEST['id'] . '.' . $ext);
$new_file_location = $outputfolder.$new_file_name;
move_uploaded_file($image_tmp, $new_file_location);
if($ext == 'jpg' || $ext == 'jpeg' ) {
$ext = 'jpg';
$src = imagecreatefromjpeg($new_file_location);
} else if($ext == 'png') {
$src = imagecreatefrompng($new_file_location);
} else {
$src = imagecreatefromgif($new_file_location);
}
list($width,$height) = getimagesize($new_file_location);
// width of the main image
$new_width = 748;
$new_height = ($height / $width) * $new_width;
$img_dest = imagecreatetruecolor($new_width,$new_height);
imagecopyresampled($img_dest,$src,0,0,0,0,$new_width,$new_height,$width,$height);
$resizedLocation = $outputfolder."resized_".$new_file_name;
imagejpeg($img_dest,$resizedLocation,100);
imagedestroy($src);
imagedestroy($img_dest);
$file_content = file_get_contents($resizedLocation);
$data_url = 'data:image/jpeg;base64,' . base64_encode($file_content);
$json = json_encode(array(
'dataUrl' => $data_url,
'extension' => $ext,
'id' => $_REQUEST['id'],
'name' => $image,
'newFileName' => $new_file_name,
'type' => $image_type
));
echo $json;
?>
Your HTML/JS stays untouched.
Now this works for me flawlessly, the only thing you have to make sure
the $outputfolder is writeable by the linux user under which the webeserver executing the php script is runnging (typically web-data...)
My web server:
CentOS Linux release 7.0.1406 (Core)
php.x86_64 5.4.16-23.el7_0.3
apache x86_64 2.4.6

Related

How can I save a modified image in Laravel

I'm trying to save a new photo in database which is modified, I have my javascript ( darkroomjs) for cropping photos, but the new photo doesn't save in database. I'd like to save my new photo instead of the original photo.
$profile_images = $request['profilefiles'];
$profile_images = explode(";;", $profile_images);
array_shift($profile_images);
$image = "";
foreach ($profile_images as $key => $value) {
$image_parts = explode(";base64,", $value);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$destinationPath = public_path('images/model/');
$hardPath = str_random(10) . '.' . $image_type;
$filename = $destinationPath . $hardPath;
file_put_contents($filename, $image_base64);
$image = $hardPath;
}
$model->title = $request['title'];
$model->slug = Slugify::slugify($request['title']);
$model->phone = $request['phone'];
$model->external_link = $request['external_link'];
$model->email = $request['email'];
$model->description = $request['description'];
$model->category = $request['category'];
$model->instagram = $request['instagram'];
$model->category_id = $request['category_id'];
$model->badges_id = $request['badges_id'];
$model->height = $request['height'];
$model->boost = $request['boost'];
$model->waist = $request['waist'];
$model->hips = $request['hips'];
$model->shoes = $request['shoes'];
$model->hair = $request['hair'];
$model->eyes = $request['eyes'];
$model->dress = $request['dress'];
$model->publish = $publish;
$model->age = date('Y-m-d', strtotime($request['dob']));
$model->metatitle = $request['title'];
$model->metadescription = substr(strip_tags($request['description']), 0, 160);
if ($image != "") {
var_dump($image);
$model->image = $image;
}
$model->upload_pdf = $upload_pdf;
$model->save();
Above image shows callback to get edited image.
1) You can save this file somewhere in temp folder at server by making ajax call to server.
2) During you save other fields(POST request). You can simply move file from temp folder to your images folder and file name into DB.
Ref : https://github.com/MattKetmo/darkroomjs
You can simply
$path = Storage::put('images/model', $image_base64);
This will create you a unique name and save it in your storage/app rather than public (which is what you need to do rather than saving in public/ directory itself).

Ajax data not being displayed after upload

Currently my entire code is working almost flawlessly, how ever upon upload the ajax data is not being displayed on my webpage after a successful upload.
Below is the code I am using (completely) because I am rather new and have been reviewing various stack over flow posts to guide me in building this.
Sorry for lack of structure below.. I don't know how to adapt to stack overflows structure requirements..
The actual form input / submit
<form action="upload2.php" class="upload" enctype="multipart/form-data" id="upload" method="post" name="upload">
<fieldset>
<legend>Uplaod Files</legend> <input id="file" multiple name="file[]" required="" type="file"> <input id="submit" name="submit" type="submit" value="upload">
</fieldset>
<div class="bar">
<span class="bar-fill" id="pb"><span class="bar-fill-text" id="pt"></span></span>
</div>
<div class="uploads" id="uploads"></div>
</form>
Here's the PHP code I am using to upload the file.
<?
header('Content-Type: application/json');
$upload = [];
$allowed = ['mp3', 'm4a'];
$succeeded = [];
$failed = [];
if (!empty($_FILES['file'])) {
foreach ($_FILES['file']['name'] as $key => $name) {
if ($_FILES['file']['error'][$key] === 0) {
$temp = $_FILES['file']['tmp_name'][$key];
$file_name = $_FILES['file']['name'][$key];
$file_size = $_FILES['file']['size'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
$s = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 4)), 0, 4);
$file = $s . '.' . $ext;
$data = $file_name . PHP_EOL . $file_size;
file_put_contents('d/' . $s . '.txt', $data);
if (in_array($ext, $allowed) === true && move_uploaded_file($temp, "v/{$file}") === true) {
$succeeded[] = array(
'name' => $name,
'file' => $file,
);
} else {
$failed[] = array(
'name' => $name
);
}
}
}
if (isset($_POST['ajax'])) {
echo json_encode(array(
'succeeded' => $succeeded,
'failed' => $failed
));
}
}
Below is javascript event listener + the returned data from ajax
document.getElementById('submit').addEventListener('click', function (e) {
e.preventDefault();
var f = document.getElementById('file'),
pb = document.getElementById('pb'),
pt = document.getElementById('pt');
app.uploader({
files: f,
progressBar: pb,
progressText: pt,
processor: 'upload2.php',
finished: function (data) {
var uploads = document.getElementById('uploads'),
succeeded = document.createElement('div'),
failed = document.createElement('div'),
anchor,
span,
x;
if (data.failed.length) {
failed.innerHTML = '<p>file didnt upload<\/p>';
}
uploads.innerText = '';
for (x = 0; x < data.succeeded.length; x = x + 1) {
anchor = document.createElement('a');
anchor.href = 'uploads/' + data.succeeded[x].file;
anchor.innerText = data.succeeded[x].name;
archor.target = '_blank';
console.log(anchor);
succeeded.appendChild(anchor);
}
uploads.appendChild(succeeded);
},
});
});
Below is the javascript we're using for ajax (I think the issue is here but I keep reviewing it and I'm not able to find the problem.)
var app = app || {};
(function (o) {
"use strict";
var ajax, getFormData, setProgress;
ajax = function (data) {
var xmlhttp = new XMLHttpRequest(),
uploaded;
xmlhttp.addEventListener('readystatechange', function () {
if (this.readystate === 4) {
if (this.status === 200) {
uploaded = JSON.parse(this.response);
if (typeof o.options.finished === 'function') {
o.options.finished(uploaded);
}
} else {
if (typeof o.options.error === 'function') {
o.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress', function (event) {
var percent;
if (event.lengthComputable === true) {
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
xmlhttp.open('post', o.options.processor);
xmlhttp.send(data);
};
getFormData = function (source) {
var data = new FormData(),
i;
for (i = 0; i < source.length; i = i + 1) {
data.append('file[]', source[i]);
}
data.append('ajax', true);
return data;
};
setProgress = function (value) {
if (o.options.progressBar !== undefined) {
o.options.progressBar.style.width = value ? value + '%' : 0;
}
if (o.options.progressText !== undefined) {
o.options.progressText.innerText = value ? value + '%' : '';
}
};
o.uploader = function (options) {
o.options = options;
if (o.options.files !== undefined) {
ajax({});
ajax(getFormData(o.options.files.files));
}
}
}(app));
My file is uploading, the progress bar is working and without returning e.preventDefault(); when it redirect to upload2.php I'm able to see the contents of the json i really don't know what my problem could be..
First of all, you have a typo in anchor here:
archor.target = '_blank';
Maybe this throws error and stops other code execution
Also you could check if your uploads div is visible via element inspector in browser.
If console.log shows nothing - do you mean by this it is not even called or it shows undefined? If it doesn't show at all, then look into the for that uses data.succeeded.length param as a limit - maybe it equals 0 and thus console.log is never called

Splice, Upload, and Re-Combine File Blobs

I am currently working on an upload system with a combination of Javascript and PHP. The Javascript essentially reads a file in by splicing blobs of cutoffSize size (or, the remaining file size, if less). Each splice is sent to the php script via Post. Then, the PHP script re-assembles the file blob by blob.
However, in my implementation (as shown below), the output file is too large. I am not sure why the file is not being written correctly, but I believe that I have localized the problem to the php script. All of my javascript testing appears to have succeeded. However, I have included the Javascript as well, just in case.
I believe the problem may be in the way I write/append files. Unfortunately, I am not sure how to move forward, so I cannot investigate this further or describe in more detail.
Any help would be greatly appreciated.
Javascript:
function getBigStringAndPost(files,i,p) {
var key = $("#keyText")[0].value
var reader = new FileReader();
var blob = files[i].slice(p*cutoffSize,Math.min((p+1)*cutoffSize,files[i].size));
var folderName = $("#folderInput")[0].value;
reader.onload = function(e) {
var result = reader.result;
console.log(result.length);
$.post("http://brandonquinndixon.com/PHP/uploadFile.php",{
uploadKey: key,
doUpload: 1,
folderName: folderName,
splitPart: p,
fileName: files[i].name,
fileContents: reader.result
},function(e) {
console.log(e);
if ((p+1)*cutoffSize<files[i].size) {
currentUploaded += cutoffSize;
updateProgressBar();
reader.abort();
getBigStringAndPost(files,i,p+1);
} else {
$("#statusDiv").html($("#statusDiv").html()+"<p class='normalP'>File: "+files[i].name+" uploaded successfully.</p>");
currentUploaded += files[i].size%cutoffSize;
updateProgressBar();
reader.abort();
loadNextFile(files,i+1);
}
});
};
reader.onerror = function(e) {
console.log(e);
totalSizeOfFiles -= files[i].size;
$("#statusDiv").html($("#statusDiv").html()+"<p class='normalP'>File: "+files[i].name+" could not be read.</p>");
loadNextFile(files,i+1);
};
reader.readAsBinaryString(blob);
}
PHP:
$targetDir = $_SERVER['DOCUMENT_ROOT']."/Downloads";
$getKey = $_POST['uploadKey'];
$data = array();
error_log("upload attempt started");
//first, check the upload key
if ($getKey !== $uploadKey) {
$data['status'] = "failure";
$data['message'] = "Incorrect Upload Key";
error_log("bad key");
} else if ($_POST['doUpload'] == 1) {
$fileName = "";
if ($_POST['folderName']!=="") {
$folderName = cleanInput($_POST['folderName']);
if (!is_dir($targetDir."/".$folderName)) {
mkdir($targetDir."/".$folderName, 0777, true);
}
$fileName = $targetDir."/".$folderName."/".$_POST['fileName'];
} else {
$fileName = $targetDir."/".$_POST['fileName'];
}
/*
Don't allow executables
*/
if (strpos($fileName,".exe") > -1 || strpos($fileName,".sh") > -1 || strpos($fileName,".deb") > -1 || strpos($fileName,".rpm") > -1) {
$data['status'] = 'failure';
$data['message'] = 'Executable type files are not allowed';
} else {
if ($_POST['splitPart'] == 0) {
overWriteFile($fileName,$_POST['fileContents']);
$data['type'] = 'overWrite';
$data['details'] = 'P '.$_POST['splitPart'];
} else {
appendFile($fileName,$_POST['fileContents']);
$data['type'] = 'append';
$data['details'] = 'P '.$_POST['splitPart'];
}
$data['status'] = 'success';
}
} else {
$data['status'] = 'success';
$data['type'] = 'none';
error_log("success, no upload");
}
echo json_encode(array($data));
function overWriteFile($fName,$fContents) {
$fName = lookupFile($fName);
$file = fopen($fName,"w");
fwrite($file,$fContents);
fclose($file);
}
/*
Append to end of file
*/
function appendFile($fName,$fContents) {
$fName = lookupFile($fName);
//$file = fopen($fName,"a");
//fwrite($file,$fContents);
//fclose($file);
file_put_contents($fName,$fContents,FILE_APPEND);
}

Upload chunked file using XHR and web workers

Hi everyone and happy new year :)
I want to upload a file using XHR and web workers, sending chunks of the file and merging at the end. The problem is that the end file is empty, I think that the issue is in the content type of XHR request that will should send a correct "multipart/form-data" (when uploading a chunk), since that PHP print_r($_FILES) returns an empty Array() but in the web worker it's not possible to use FormData(). Help me to resolve this trouble, please :'(
index.html
<form onsubmit="return false" enctype="multipart/form-data">
<input id="file" type="file">
<div id="filedrop">or drop files here</div>
</form>
<script>
window.addEventListener("load", function() {
var fileselect = document.getElementById("file");
fileselect.addEventListener("change", FileSelectHandler, false);
var filedrag = document.getElementById("filedrop");
filedrag.addEventListener("dragover", FileDragHover, false);
filedrag.addEventListener("dragleave", FileDragHover, false);
filedrag.addEventListener("drop", FileSelectHandler, false);
}, false);
function FileDragHover(e) {
e.stopPropagation();
e.preventDefault();
}
function FileSelectHandler(e) {
FileDragHover(e);
var blob = e.target.files[0] || e.dataTransfer.files[0];
worker = new Worker("upload.webworker.js");
worker.postMessage(blob);
worker.onmessage = function(e) {
console.log(e);
};
}
</script>
uploadFile.php
<?
if ($_GET['a'] == "chunk") {
$target = "upload/" . $_GET['name'] . '-' . $_GET['index'];
move_uploaded_file($_FILES['file']['tmp_name'], $target);
sleep(1);
} else {
$target = "upload/" . $_GET['name'];
$dst = fopen($target, 'wb');
$slices = (int)$_GET['slices'];
for ($i = 0; $i < $slices; $i++) {
$slice = $target . '-' . $i;
$src = fopen($slice, 'rb');
stream_copy_to_stream($src, $dst);
fclose($src);
unlink($slice);
}
fclose($dst);
}
?>
upload.webworker.js
function uploadChunk(blob, index, start, end, slices, slices2) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
slices--;
if (slices == 0) {
var xhrMerge = new XMLHttpRequest();
xhrMerge.open("POST", "uploadFile.php?a=merge&name=" + blob.name + "&slices=" + slices2);
xhrMerge.onload = function() {
self.close();
};
xhrMerge.send();
}
};
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) self.postMessage(Math.round(100 / e.total * e.loaded)); //this doesn't work o.O
};
var chunk = blob.slice(start, end);
xhr.open("POST", "uploadFile.php?a=chunk&name=" + blob.name + "&index=" + index);
xhr.setRequestHeader("Content-Type", "multipart\/form-data; boundary=--------------------");
xhr.send(chunk);
}
self.onmessage = function(e) {
const BYTES_PER_CHUNK = 1024 * 1024 * 32;
var blob = e.data,
start = 0,
index = 0,
slices = Math.ceil(blob.size / BYTES_PER_CHUNK),
slices2 = slices;
while (start < blob.size) {
end = start + BYTES_PER_CHUNK;
if (end > blob.size) end = blob.size;
uploadChunk(blob, index, start, end, slices, slices2);
start = end;
index++;
}
};
PS: if you want, tell me please how to optimize the upload in general =)
PPS: I'll should take advantages using synchronous ajax requests (only in the web worker) ?
PPPS: and if I to use php://input for reading chunk, it's better ?
I resolved reading file from php://input with this code:
$putdata = fopen("php://input", "r");
$fp = fopen($target, "w");
while ($data = fread($putdata, 16384)) {
fwrite($fp, $data);
}
fclose($fp);
fclose($putdata);
In this way, I don't need to write the HTTP headers of the multipart/form-data

Trying to detect when download is ready

I am trying to create a zip folder on the fly. The zip will hold images that a user has selected from a library that is hosted on Amazon S3. Below is the code I have so far.
REQUEST URL FROM POST
function download_multi() {
//$user_id, $files, $project_id, $project_name
$this->load->library('aws');
$user = User::get_user();
$requestedHashes = $this->input->post("files");
$files = array();
foreach($requestedHashes as $hash) {
$files[] = hex_to_string($hash);
}
$project_id = $this->input->post("projectid");
$project = new Project($project_id);
$project_name = $project->project_name;
$this->aws->create_zip($user->id, $files, $project_id, $project_name, (int)$this->input->post("downloadToken"));
}
Create Zip
public function create_zip($user_id, $files, $project_id, $project_name, $cookie) {
//create a random folder name to avoid collision.
$this->folder = md5(time() . rand());
if(!mkdir('./files' . '/' . $this->folder, 0777, TRUE)) {
exit("Folder not created\n");
}
//create zipfile
$this->filename = $this->local_file_path . $this->folder . '/files.zip';
$zip = new ZipArchive();
if ($zip->open($this->filename, ZIPARCHIVE::CREATE) !== TRUE) {
exit("cannot open <$this->filename>\n");
}
//create options for downloading each file to the server
//temporarily to add to archive
$opt = array('preauth' => '+1 minutes');
//download each file to the server.
foreach ($files as $file) {
//generate a link.
$response = $this->s3->get_object($this->bucket, $this->_make_path($user_id, $project_id) . $file, $opt);
//get filename.
$file_name = explode('?', basename($response));
//add filename to array
$local_files[] = $file_name[0];
//copy the file from aws to local server.
if(copy($response, $this->local_file_path . $this->folder . '/' . $file_name[0])) {
$zip->addFile($this->local_file_path . $this->folder . '/' . $file_name[0], $file_name[0]);
}
}
//close zip
$zip->close();
//die(var_dump(file_exists($this->filename)));
//kill each temp file
/*foreach ($local_files as $file) {
unlink($this->local_file_path . $this->folder . '/' . $file);
}*/
//load download helper.
$this->ci->load->helper('download');
//download
stream_download("APP_{$project_name}_" . time() . ".zip", $this->filename, $cookie);
}
The Download Helper
function stream_download($filename = '', $data = '', $cookie = NULL)
{
//die($cookie);
if ($filename == '' OR $data == '')
{
return FALSE;
}
// Try to determine if the filename includes a file extension.
// We need it in order to set the MIME type
if (FALSE === strpos($filename, '.'))
{
return FALSE;
}
// Grab the file extension
$x = explode('.', $filename);
$extension = end($x);
// Load the mime types
if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/mimes.php'))
{
include(APPPATH.'config/'.ENVIRONMENT.'/mimes.php');
}
elseif (is_file(APPPATH.'config/mimes.php'))
{
include(APPPATH.'config/mimes.php');
}
// Set a default mime if we can't find it
if ( ! isset($mimes[$extension]))
{
$mime = 'application/octet-stream';
}
else
{
$mime = (is_array($mimes[$extension])) ? $mimes[$extension][0] : $mimes[$extension];
}
// Generate the server headers
if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE") !== FALSE)
{
header('Content-Type: "'.$mime.'"');
header('Set-Cookie: fileDownloadToken="'.$cookie.'"');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Transfer-Encoding: binary");
header('Pragma: public');
header("Content-Length: ".filesize($data));
}
else
{
header('Content-Type: "'.$mime.'"');
header('Set-Cookie: fileDownloadToken="'.$cookie.'"');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Pragma: no-cache');
header("Content-Length: ".filesize($data));
}
flush();
}
JAVASCRIPT
downloadSelectedFiles: function(e) {
//window.XmlHttpRequest = new XmlHttpRequest();
console.log("Block UI");
var that = this;
var url = config.base + "projects/download_multi";
var projectId = $("li.selected").find('li.js-select-file').data('projectid');
var images = {};
images.hashes = [];
var token = new Date().getTime();
$("li.selected").each(function(i){
images.hashes.push($(this).find('li.js-select-file').data('filename'));
});
//window.location.href = url;
$.post(url, { files: images.hashes, projectid: projectId, downloadToken: token }, function(data){
var fileDownloadCheckTimer = window.setInterval(function() {
console.log("checking...");
var cookieValue = $.cookie('fileDownloadToken');
console.log(parseInt(cookieValue), parseInt(token));
if( parseInt(cookieValue) == parseInt(token) ) {
that.finishDownload()
} else {
console.log("Don't Match");
}
}, 1000);
/*var iframe = document.createElement("iframe");
iframe.src = config.base + data;
iframe.style.display = "none";
document.body.appendChild(iframe);
return false;*/
});
},
finishDownload: function() {
window.clearInterval(fileDownloadCheckTimer);
$.removeCookie('fileDownloadToken');
console.log("Unblock UI");
}
One thing I have noticed is that when I am checking to see of the cookie value and the token match one is a string and the other an int. Other that I also not that I only get the headers in my reposonse, I never actually get the download window.

Categories