Splice, Upload, and Re-Combine File Blobs - javascript

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);
}

Related

HTML JS PHP File chunk upload

I am working with a file chunking solution ( cant remember where I found it ) but I have modified the solution to my needs.
The issue is that although most of the time the file will upload successfully sometimes I get an error
Uncaught SyntaxError: Unexpected token < in JSON at position 0
I also get another error at the same time
( unlink(test/H2jig-6.png): Resource temporarily unavailable in ... )
I was hoping that you guys will be able to spot the issue in my code that is causing this problem. I think that it manages to unlink the files too early before the uploads are done and then is unable to find them.
Upload file HTML/JS
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>test upload by chunk</title>
</head>
<body>
<input type="file" id="f" />
<script>
function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
(function() {
var f = document.getElementById('f');
if (f.files.length)
processFile();
f.addEventListener('change', processFile, false);
function processFile(e) {
var scount = 0;
var file = f.files[0];
console.log(file);
var ext = file.name.split('.').pop();
ext = '.'+ext;
var size = file.size;
var sliceSize = 250000;
var num_of_slices = Math.ceil(size / sliceSize);
var fileid = makeid();
var start = 0;
setTimeout(loop, 1);
function loop() {
var end = start + sliceSize;
if (size - end < 0) {
end = size;
}
var s = slice(file, start, end);
scount ++;
send(s, start, end,scount,size,num_of_slices,ext,fileid);
if (end < size) {
start += sliceSize;
setTimeout(loop, 1);
}
}
}
function send(piece, start, end,scount,size,num_of_slices,ext,fileid) {
var formdata = new FormData();
var xhr = new XMLHttpRequest();
xhr.open('POST', 'uploadchunk2.php', true);
formdata.append('start', start);
formdata.append('end', end);
formdata.append('file', piece);
formdata.append('scount', scount);
formdata.append('fsize', size);
formdata.append('num_of_slices', num_of_slices);
formdata.append('ext', ext);
formdata.append('fileid', fileid);
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
console.log(myArr);
// myFunction(myArr);
}
};
xhr.send(formdata);
}
/**
* Formalize file.slice
*/
function slice(file, start, end) {
var slice = file.mozSlice ? file.mozSlice :
file.webkitSlice ? file.webkitSlice :
file.slice ? file.slice : noop;
return slice.bind(file)(start, end);
}
function noop() {
}
})();
</script>
</body>
</html>
PHP upload
<?php
$target_path = '/test/';
$tmp_name = $_FILES['file']['tmp_name'];
$filename = $_FILES['file']['name'];
$target_file = $target_path.$filename;
$num_chunks_uploaded = $_POST['scount'];
$num_chunks_created = $_POST['num_of_slices'];
$extension = $_POST['ext'];
$file_id = $_POST['fileid'];
$file_location = 'test/';
$file_path = $file_location.$file_id.$extension;
$chunked_file_path = $file_location.$file_id.'-'.$num_chunks_uploaded.$extension;
move_uploaded_file(
$_FILES['file']['tmp_name'],
$chunked_file_path
);
// count amount of uploaded chunks
$chunksUploaded = 0;
for ($i=1; $i <= $num_chunks_created ; $i++) {
if ( file_exists($file_location.$file_id.'-'.$i.$extension) ) {
++$chunksUploaded;
}
}
// when this triggers - that means the chunks are uploaded
if ($chunksUploaded == $num_chunks_created) {
/* here you can reassemble chunks together */
for ($i = 1; $i <= $num_chunks_created; $i++) {
$file = fopen($file_location.$file_id.'-'.$i.$extension, 'rb');
$buff = fread($file, 2097152);
fclose($file);
$final = fopen($file_path, 'ab');
$write = fwrite($final, $buff);
fclose($final);
unlink($file_location.$file_id.'-'.$i.$extension);
}
}
$data = $chunksUploaded;
header('Content-Type: application/json');
echo json_encode($_POST);
?>
This isn't the answer to your problem, but it solves one problem you do have in your JavaScript.
PHP requires that a MAX_FILE_SIZE field be sent with uploaded files. This field must appear before the file field in the POST variables. So you need to add:
formdata.append('MAX_FILE_SIZE', 1000000) // or whatever you want the max size to be
before the field containing the file to be sent.

Ajax post has previous data

This is driving me crazy. I know I am doing something wrong but what? The problem is I am getting previous data in my ajax call when I post it to php.
Story: I click upload button which calls JavaScript loadme() where i am cleaning the input type file element. I then select file/files and click upload which calls doit() which internally calls uploadFiles(). UploadFiles makes an array with loaded images and post it to the php file through ajax.
I have tried plain javascript and jquery to clean file input element and php to set post values to null after using it, but still i am getting the previous values.
The form
<form id="theform" method="post" action="" enctype="multipart/form-data" target="multifile">
<input type="hidden" id="folderpath" name="folderpath" value="<?=htmlspecialchars($path)?>">
<input name="upfiles[]" id="upfiles" type="file" multiple="" />
</form>
Javascript
async function doit(){
//some code
uploadFiles();
}
function loadmeup(){
$('upfiles').value = '';
$('uploadbox').show();
}
function closeupload(){
$('uploadbox').hide();
}
var masterFileArray = [];
var left_loaded_count = 0;
var progress = 0;
function uploadFiles() {
var files = document.getElementById("upfiles").files;
var path = document.getElementById('folderpath').value;
var numOfFiles = files.length;
alert(numOfFiles);
if (files && numOfFiles>0) {
for (var i = 0, f; f = files[i]; i++) {
if(checkExtension(f.name) && checkSize(f.size)){
progress = i+1/numOfFiles;
var r = new FileReader();
r.onload = (function (f) {
return function (e) {
var contents = e.target.result;
masterFileArray.push({name:f.name, contents: contents, type:f.type, size:f.size});
console.log(f.name);
left_loaded_count -= 1;
if(left_loaded_count == 0)
{
var filesarray = null;
filesarray = JSON.stringify(masterFileArray);
console.log("after stringify: "+filesarray.length);
new Ajax.Request('upload_do.php', {
method: 'post',
parameters: {files: filesarray, folderpath:path},
onSuccess: function(transport){
var response = transport.responseText;
parent.notify(response);
closeupload();
get_listview(currlist,sort);
}
});
}
};
})(f);
left_loaded_count += 1;
r.readAsDataURL(f);
}
else{
alert('Invalid file extension or size ' + f.name);
if(progress==0)
location.reload();
}
}
} else {
alert('Failed to load files');
closeupload();
}
}
PHP
try{
$error = null;
$files = json_decode($_POST['files'],true);
$numFiles = 0;
foreach($files as $file){
$output = $reso->writeUpload($file['contents'], $file['name']);
$numFiles++;
}
}
catch (Exception $ex){
$error = $ex->getMessage();
$GLOBALS['log']->log($error);
}
isset($_POST['files'])? $_POST['files'] = null: '';
if (!is_null($error))
echo _($error);
else
echo _($numFiles.' file'.(($numFiles > 1) ? 's' : '').' successfully
uploaded');

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

fwrite() returns int(0) when called

I'm trying to use fcimg and wkhtmltoimage in order to export a chart to a PDF report. I keep getting an error from fcimg saying "Fatal error: Uncaught exception 'FCImageException' with message 'There was an error with wkhtmltopdf'[...]".
By debbuging the function inside de fcimg library I've noticed that a couple of 'fwrite()' functions in charge of writing the minified JS scripts of FusionCharts into the file are returning a value of '0' (no writing, but no error), even do the string to write is properly saved into a variable (as the code below). Is there some kind of limit or restrinction to the 'fwrite' function that I'm not aware of? Previous calls to the function work just fine. Any help or advice would be really appreciated.
[...]
function fusioncharts_to_image($outputFilePath, $swfName, $inputString, $height, $width, $options = array())
{
$jsonFlag = false;
if($inputString[0] === '<') // Check for the first character
{
// do nothing. jsonFlag is set to false anyways
}
else if($inputString[0] === "{")
{
$jsonFlag = true;
}
else
{
throw new FCImageException("The input string doesn't seem to be either JSON or XML");
}
$fileType = "png";
if(isset($options['imageType']))
$fileType = $options['imageType'];
$renderDelay = 1000;
if (isset($options['render_delay']) && is_numeric($options['render_delay']))
$renderDelay = $options['render_delay'];
/*
* Note: sys_get_temp_dir returns /tmp on Linux (don't know about osx)
* but on the other hand, it returns C:\user\foo\Local\Temp\ on Windows
*
* so we need to add a directory separator on Linux but not on windows
*/
$separator = "";
if(DIRECTORY_SEPARATOR === "/") // check if unix system. TODO: There will be better ways to do this
$separator = DIRECTORY_SEPARATOR;
$imageFileName = sys_get_temp_dir().$separator."\FCImage".rand(0, 1000).'.'.$fileType;
// $imageFileName = sys_get_temp_dir().”\FCImage”.rand(0, 1000).’.’.$fileType;
// $imageFileName = 'C:\PRUEBA\FCImage'.rand(0, 1000).'.'.$fileType;
$cwd = __DIR__; // change working directory to the current script's directory
$env = array(); // set any environment variables here
// configure the arguments
$args = "--format $fileType";
$args = $args." --crop-w ".($width - 1);
$args = $args." --crop-h ".($height - 1);
if(isset($options['nodelay']))
{
if($options['nodelay'] === true)
$args = $args." --javascript-delay 0";
}
else
{
$args = $args." --javascript-delay {$renderDelay}";
}
if(isset($options['quality']))
{
$args = $args." --quality {$options['quality']}";
}
$debugFlag = false;
if(isset($options['debug']))
{
$debugFlag = true;
$debugFile = fopen("debug.html", "w");
echo "\n\nCall to:\n fusioncharts_to_image ($outputFilePath, $swfName, [removing input string], $height, $width)";
}
// now, determine the platform this is running on
$os = php_uname("s");
$arch = php_uname("m");
if($os==="Windows NT"){
$platform = _FC_IMG_PLATFORM_WINDOWS;
// var_dump($platform);
}
else if($os === "Linux")
{
if($arch === "i386")
$platform = _FC_IMG_PLATFORM_LINUX;
else if($arch === "i686")
$platform = _FC_IMG_PLATFORM_LINUX;
else if ($arch === "x86_64")
$platform = _FC_IMG_PLATFORM_LINUX_64;
else
throw new FCImageException ("This Linux architecture is not supported");
}
else if($os === "Darwin") {
$platform = _FC_IMG_PLATFORM_OSX;
}
else
throw new FCImageException("Your server OS is currently not supported");
$fcRoot = dirname(__FILE__);
$wkCommand = $platform;
if(isset($options['wkhtmltoimage_path'])) {
$wkCommand = $options['wkhtmltoimage_path'];
}
$command = "$wkCommand $args - $imageFileName";
// var_dump($command); echo "<br>";
if($debugFlag)
{
echo "\n Command: $command";
}
$wkstdin = popen($command, "w");
// var_dump($wkstdin);
if(!is_resource($wkstdin))
{
throw new FCImageException("An error took place while trying to open wkhtmltopdf");
}
$templateHead = <<<TOP
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style>
body{
padding:0 0 0 0;
margin:0 0 0 0;
}
</style>
<script>
TOP;
// ok. write template.txt into the process stdin
fwrite($wkstdin, $templateHead);
if($debugFlag)
{
fwrite($debugFile, $templateHead);
}
$contFC = file_get_contents($options['licensed_fusioncharts_js']);
$contFCC = file_get_contents($options['licensed_fusioncharts_charts_js']);
// echo $contFC;
// echo $contFCC;
if(isset($options['licensed_fusioncharts_charts_js']) && isset($options['licensed_fusioncharts_js'])) {
$temp1 = fwrite($wkstdin, $contFC);
var_dump($temp1);
$temp2 = fwrite($wkstdin, $contFCC);
var_dump($temp2);
if($debugFlag)
{
fwrite($debugFile, file_get_contents($options['licensed_fusioncharts_js']));
}
if($debugFlag)
{
fwrite($debugFile, file_get_contents($options['licensed_fusioncharts_charts_js']));
}
}
else {
throw new FCImageException("Need to provide fusioncharts licensed version here");
}
$functionToCall = "setXMLData";
if($jsonFlag === true)
$functionToCall = "setJSONData";
// replace all EOL with ""
$escapedData = str_replace("\n", "", $inputString);
$escapedData = addslashes($escapedData);
$templateCode = "</script>
</head>
<body>
<div id='chartContainer'><small>Loading chart...</small></div>
</body>
<script>
FusionCharts.setCurrentRenderer('javascript');
var chart = new FusionCharts('$swfName', 'chart0', '$width', '$height', '0', '1');
chart.$functionToCall('$escapedData');
chart.render('chartContainer');
</script>
</html>";
$temp = fwrite($wkstdin, $templateCode);
var_dump($temp);
if($debugFlag)
{
fwrite($debugFile, $templateCode);
}
$returnCode = pclose($wkstdin);
// echo(var_dump($returnCode)." returnCode");
if($returnCode !== 0)
{
// var_dump($imageFileName);
if(file_exists($imageFileName)){
unlink($imageFileName);
}
throw new FCImageException("There was an error with wkhtmltopdf ");
}
// success!
rename($imageFileName, $outputFilePath);
return true;
}

PHP Image Upload Not Resizing When Sent Via JS

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

Categories