Dlib for javascript - javascript

I am fairly new to C++ and also Dlib. I need to work on a facial landmark detector for browser and was wondering if someone has tried compiling DLIB with e.g. ASM.js to work on a browser. I have not seen many DLib facial landmarking live demos on the web.
Is it a worthwhile idea to pursue? If yes, could someone direct me to any resources?

I am also face same problem in one of the my project. But i successfully get face landmark details from dlib with browser.
Actually i get image from user and send to server save it one specific folder. then trigger dlib python code through PHP and get landmark point details as a json format. once we get a point details we can do anything with that.
idea is
input image file --> send to serve --> save to folder --> trigger dlib python script --> save point as a json file --> echo to success --> get json
through this way:
STEP 1:
first install Dlip on your server successfully(first tested your local server) without any error. and check it its run without error.
STEP 2:
Then we want face landmark from dlip. dlip have a example script face_landmark_detection.py we can use this.
my customized face_landmark_detection.py script this is save point details as a json file in specific path:
# python face_landmark_detection.py "predictor.dat" "folder/image.jpg" "folder/test.json"
import dlib
import glob
import json
import os
from skimage import io
import sys
predictor_path = sys.argv[1]
#faces_folder_path = sys.argv[2]
image = sys.argv[2]
json_path = sys.argv[3]
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(predictor_path)
img = io.imread(image)
dets = detector(img, 1)
print(dets);
print("Number of faces detected: {}".format(len(dets)))
for k, d in enumerate(dets):
print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(
k, d.left(), d.top(), d.right(), d.bottom()))
# Get the landmarks/parts for the face in box d.
shape = predictor(img, d)
print("Part 0: {}, Part 1: {}, Part 3: {} ...".format(shape.part(0),
shape.part(1), shape.part(2), ))
part1 = shape
data = {}
num = 0
for n, p in enumerate(shape.parts()):
n = format(n)
p = format(p)
p = p.split(",")
x = p[0].split("(")
x = x[1]
y = p[1].split(" ")
y = y[1].split(")")
y = y[0]
print(n, x, y)
data[n] = {'x':x, 'y':y}
out_file = open(json_path, "a")
json.dump(data, out_file, sort_keys=True, indent=4)
json_data = json.dumps(data, sort_keys=True);
print(json_data)
my server php script . this script get image from browser and save it in some folder and trigger my face_landmark_detection.py with predictor path ,image path, json path arguments.
server.php file like this
<?php
$target_dir = "/designing/face/uploads/";
$type = explode("/", $_FILES["file"]["type"]);
$type = $type[1];
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file, PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if (isset($_POST)) {
$check = getimagesize($_FILES["file"]["tmp_name"]);
if ($check !== false) {
$uploadOk = 1;
} else {
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
unlink($target_file);
$uploadOk = 1;
}
// Check file size
/* if ($_FILES["file"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
} */
// Allow certain file formats
if ($imageFileType != "jpg" && $imageFileType != "jpeg" && $imageFileType != "png") {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "error";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
//chmod($target_file, 0777);
//echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
if ($imageFileType == "png") {
$image = imagecreatefrompng($target_file);
$bg = imagecreatetruecolor(imagesx($image), imagesy($image));
imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
imagealphablending($bg, TRUE);
imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
imagedestroy($image);
$quality = 100; // 0 = worst / smaller file, 100 = better / bigger file
imagejpeg($bg, $target_file . ".jpg", $quality);
imagedestroy($bg);
unlink($target_file);
$target_file = $target_file . ".jpg";
//echo $target_file;
}
$json_file = fopen("/test/json/" . $_FILES["file"]["name"] . "_json.txt", "w");
if ($json_file) {
$command = 'python /face/face_landmark_detection.py "/face/predictor.dat" "' . $target_file . '" "/test/json/' . $_FILES["file"]["name"] . '_json.txt"';
$output = shell_exec($command);
if ($output) {
//unlink($target_file);
echo "ok";
}
}
//echo $command;
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
and my client (browser) side script like this
$('#file').change(function() {
var formData = new FormData();
formData.append('file', $('input[type=file]')[0].files[0]);
img = $('input[type=file]')[0].files[0];
file_name = img.name;
console.log(file_name);
var reader = new FileReader();
reader.onload = function(readerEvt) {
data_url = readerEvt.target.result;
};
reader.readAsDataURL(img);
$.ajax({
url: base_url + "server.php",
type: 'POST',
data: formData,
success: function(data) {
console.log(data);
if (data === "ok") {
getJson(data_url, file_name);
} else {
alert("something worng");
}
},
cache: false,
contentType: false,
processData: false
});
});
var pts;
function getJson(data_url, file_name) {
console.log(file_name);
var json_name = {
'name': file_name
};
$.ajax({
method: "POST",
url: base_url + "get_json.php",
crossDomain: true,
data: json_name,
dataType: 'JSON',
success: function(data) {
pts = data;
console.log(pts);
// alert(data_url);
}
});
}
once everything run good we get a json file with points . We can play what we want on canvas with these point. first you have to understand the whole process.
I am directly pasting my demo code here. Look the code and change what you want (like path, parameters... ) then run.
I am successfully get point details with these way for My virtual face make over project. I cant give you a my project url for your demo because project currently under process.

Related

jQuery - Append file name to FormData and get it in a PHP script

I have the following JS code that I use to upload an image based on its path:
var data = new FormData();
data.append('fileName', fileName);
data.append('file', file);
$.ajax({
url : dbPath + "upload-file.php",
type: 'POST',
data: data,
contentType: false,
processData: false,
mimeType: "multipart/form-data",
success: function(data) {
Swal.close();
var fileURL = dbPath + data;
console.log('FILE UPLOADED TO: ' + fileURL);
This is my upload-image.php script:
<?php
$fileName = $_POST['fileName'];
if ($_FILES["file"]["error"] > 0) {
echo "Error: " .$_FILES["file"]["error"]. "<br>";
} else {
// Check file size
if ($_FILES["file"]["size"] > 20485760) { // 20 MB
echo "Sorry, your file is larger than 20 MB. Upload a smaller one.";
} else { uploadImage(); }
}// ./ If
// UPLOAD IMAGE ------------------------------------------
function uploadImage() {
// generate a unique random string
$randomStr = generateRandomString();
$filePath = "uploads/".$randomStr."".$fileName;
// upload image into the 'uploads' folder
move_uploaded_file($_FILES['file']['tmp_name'], $filePath);
// echo the link of the uploaded image
echo $filePath;
}
// GENERATE A RANDOM STRING ---------------------------------------
function generateRandomString() {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i<20; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
?>
Everything works fine in a matter of uploading a file, a JPG image for example, but my purpose is to use:
data.append('fileName', fileName);
to simply append the file name and extension to my FormData and get a file URL like this:
https://example.com/_json/uploads/03aC8qsIk4hanngqO3G4_fileName.jpg
But the $fileName variable in my PHP script fires an error_log line as Undefined index fileName in line xx, so is there a way to upload a file, get its name and extension and append it to the file URL that my PHP script generates?
I hope my question is clear, what I'm trying to do is simply a general Ajax automatic upload for any kind of file, not just images, and get their URL based on a random string + its name and extension (like .png, .mp4, .pdf, etc.).
I've figured it out, thanks to all the comments, I had to append the fileName to my FormData() and edit my PHP script as it follows:
JS:
function uploadFile() {
var dbPath = '<?php echo $DATABASE_PATH ?>';
var file = $("#file")[0].files[0];
var fileName = file.name;
console.log('FILE NAME: ' + fileName);
Swal.fire({icon: 'success', title: 'Loading...', showConfirmButton: false })
var data = new FormData();
data.append('file', file);
data.append('fileName', fileName); <!-- ADDED THIS LINE
$.ajax({
url : dbPath + "upload-file.php?fileName=" + fileName, <!-- ADDED THIS LINE
type: 'POST',
data: data,
contentType: false,
processData: false,
mimeType: "multipart/form-data", <!-- ADDED THIS LINE
success: function(data) {
Swal.close();
var fileURL = dbPath + data;
console.log('FILE UPLOADED TO: ' + fileURL);
// error
if (data.includes("ERROR:")) {
Swal.fire({ icon: 'error', title: 'Oops...', text: data, });
// show file data
} else {
$("#fileURL").val(fileURL);
$("#viewButton").attr("href", fileURL);
$("#viewButton").css("display", "block");
}
// error
}, error: function(e) {
Swal.fire({ icon: 'error', title: 'Oops...', text: 'Something went wrong: ' + e.message, });
}});
}
My upload-file.php script:
<?php include 'config.php';
if ($_FILES["file"]["error"] > 0) {
echo "Error: " .$_FILES["file"]["error"]. "<br>";
} else {
// Check file size
if ($_FILES["file"]["size"] > 20485760) { // 20 MB
echo "ERROR: Your file is larger than 20 MB. Please upload a smaller one.";
} else { uploadImage(); }
}// ./ If
// UPLOAD IMAGE ------------------------------------------
function uploadImage() {
// generate a unique random string
$randomStr = generateRandomString();
$filePath = "uploads/".$randomStr;
// upload image into the 'uploads' folder
move_uploaded_file($_FILES['file']['tmp_name'], $filePath);
// echo the link of the uploaded image
echo $filePath;
}
// GENERATE A RANDOM STRING ---------------------------------------
function generateRandomString() {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i<20; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString."_".$_POST['fileName']; <!-- ADDED THIS LINE
}
?>
Now I can finally upload any type of file and get its name + extension at the end of the URL, it works perfectly.

Trouble sending an generated jsPdf to server

I have generated an PDF using jsPdf and Html2Canvas. It works very well, and is downloadable.
I'm now aiming to get the generated .pdf saved to my server, so I can send it out via phpmailer. This is how I approached this.
function print() {
document.getElementById("out").textContent = document.getElementById("fader").value;
const filename = 'DHC_Herren_Front.pdf';
html2canvas(document.querySelector('#pdf')).then(canvas => {
let pdf = new jsPDF('l', 'mm', 'a4');
pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 298, 211, function () {
var blob = doc.output('blob');
var formData = new FormData();
formData.append('pdf', blob);
$.ajax('/st/tda/dhc/men_front/upload.php', {
method: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (data) {
console.log(data)
},
error: function (data) {
console.log(data)
}
});
});
});
}
and my upload.php
<?php move_uploaded_file(
$_FILES['pdf']['tmp_name'],
$_SERVER['DOCUMENT_ROOT'] . "/st/tda/dhc/men_front/test.pdf");
?>
My Question would be, why I end up without an File on the Server. I feel like there must be an simple solution to this, but I just can't pinpoint it.
Newest HTML
function ma() {
document.getElementById("out").textContent = document.getElementById("fader").value;
html2canvas(document.querySelector('#pdf')).then(canvas => {
var pdf = btoa(doc.output());
pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 298, 211,);
$.ajax({
method: "POST",
url: "/st/tda/dhc/men_front/upload.php",
data: {data: pdf},
}).done(function(data){
console.log(data);
});
});
}
Newest upload.php
<?php
if(!empty($_POST['data'])){
$data = base64_decode($_POST['data']);
// print_r($data);
file_put_contents( "test.pdf", $data );
} else {
echo "No Data Sent";
}
exit();
This is how I do it. Take a look and see if you can adapt it to your code. This is the uploadFiles.php that the ajax sends the file to.
<?php
$ds = DIRECTORY_SEPARATOR; // a directory separator
$cid = $_POST["cid"]; // directory name passed from the form as a variable
$rid = $_POST["rid"]; // directory name passed from the form as a variable
$storeFolder = "../recordFiles/".$cid."/".$rid; // the place where i want to save stuff
// run only if there are files sent from ajax.
if (!empty($_FILES)) {
// check if the directory exists and if not then create it.
if (!file_exists('../recordFiles/'.$cid."/".$rid)) {
mkdir('../recordFiles/'.$cid."/".$rid, 0777, true);
}
// get the temp file name
$tempFile = $_FILES['file']['tmp_name'];
// remove all whitespace in the file name
$cleanedFileName = $_FILES['file']['name'];
$cleanedFileName = preg_replace('/\s+/', '', $cleanedFileName);
// set the target path
$targetPath = dirname( __FILE__ ).$ds.$storeFolder.$ds;
// set the target file name and path
$targetFile = $targetPath.$cleanedFileName;
// move the files
move_uploaded_file($tempFile,$targetFile);
}
?>

Error 413 with POSTing large string

I'm trying to upload images using the FileReader API, and writing the data URL from the FileReader.readAsDataURL() method to a file using PHP on the server side.
The method works with smaller images (not sure exactly how small, but < 1MB is probably fairly acurate). However, when uploading larger images, I get a 413 Request Entity Too Large error. I saw this question and tried both of the solutions, however the first did nothing and the second gave a 500 error. When I checked the error log it said:
/home/username/public_html/.htaccess: LimitRequestFieldsize not allowed here
Why isn't this working?
php.ini
file_uploads = On
post_max_size = 50M
upload_max_filesize = 50M
.htaccess
RewriteEngine On
# LimitRequestFieldSize 2097152
SSLRenegBufferSize 1000000
JS
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$.ajax({
url: "?action=saveImg",
type: "POST",
dataType: "json",
data: {
image: e.target.result,
id: id
},
success: function(data){
$.dialog(data.message, data.title);
}
});
}
for(var i = 0; i < input.files.length; i++){
reader.readAsDataURL(input.files[i]);
}
}
}
$("#file").change(function() {
readURL(this);
});
PHP
$id = $_POST["id"];
$filetype = str_replace('data:', '', explode(";", $_POST["image"])[0]);
$data = $_POST["image"];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$rand = random_str(6);
$ext = explode("/", $filetype)[1];
if(!is_dir("../../images/product/{$id}/")){
mkdir("../../images/product/{$id}/");
}
$fh = fopen("../../images/product/{$id}/{$rand}.{$ext}", "w+");
fwrite($fh, $data);
fclose($fh);
$return = ["message" => "ID is $id. Saved image as /images/product/{$id}/{$rand}.{$ext}.", "title" => "Saved Image", "image" => "/images/product/{$id}/{$rand}.{$ext}"];
echo json_encode($return);
die();
How can I make this work?
This is an apache config issue
There are many potential causes of this issue, aside from LimitRequestFieldsize.
LimitRequestFieldsize
First, LimitRequestFieldsize usually must be set in a .conf file, rather than .htaccess. Additionally, there are significant security implications to increasing the limit. (slow loris attack for one)
SecRequestBodyLimit (if you're using mod_security)
Also must be set in a .conf file. Also has security implications.
SecRequestBodyLimit 10485760
Your question belongs on ServerFault

How to use the extra params in ExtJS Upload Widget by Ivan Novakov

I am using this upload widget in my web application.
I am using the FormDataUploader and I am able to upload files to a server directory quite well. However, I wanted to send extra parameters as well to the php file handling the upload. This is what I attempted:
var uploadPanel = Ext.create('Ext.ux.upload.Panel', {
uploader : 'Ext.ux.upload.uploader.FormDataUploader',
uploaderOptions : {
url : 'uploadGallery.php'
},
synchronous : true,
uploadParams : {
ID_Person : ID_Person,
ID_CI : ID_CI
}
});
As you can see, I used the uploadParams, however, my PHP couldn't seem to receive it. In my php file, I have:
$ID_Person = $_GET['ID_Person'];
$ID_CI = $_GET['ID_CI'];
However, my PHP seems to be unable to get these params.
What I did next was to use the default ExtJS Uploader as such:
var uploadPanel = Ext.create('Ext.ux.upload.Panel', {
uploaderOptions : {
url : 'uploadExtJS.php'
},
synchronous : true,
uploadParams : {
ID_Person : ID_Person,
ID_CI : ID_CI
}
});
At first, I used the old PHP file which was able to get the extra params I sent. However, it seems that I needed to use a different PHP file for the ExtJS uploader.
This is what my PHP file looks like:
<?php
/**
* Example processing of raw PUT/POST uploaded files.
* File metadata may be sent through appropriate HTTP headers:
* - file name - the 'X-File-Name' proprietary header
* - file size - the standard 'Content-Length' header or the 'X-File-Size' proprietary header
* - file type - the standard 'Content-Type' header or the 'X-File-Type' proprietary header
*
* Raw data are read from the standard input.
* The response should be a JSON encoded string with these items:
* - success (boolean) - if the upload has been successful
* - message (string) - optional message, useful in case of error
*/
require __DIR__ . '_common.php';
$config = require __DIR__ . '_config.php';
error_reporting(-1);
ini_set('display_errors', 'On');
/*
* You should check these values for XSS or SQL injection.
*/
if (!isset($_SERVER['HTTP_X_FILE_NAME'])) {
_error('Unknown file name');
}
$fileName = $_SERVER['HTTP_X_FILE_NAME'];
if (isset($_SERVER['HTTP_X_FILENAME_ENCODER']) && 'base64' == $_SERVER['HTTP_X_FILENAME_ENCODER']) {
$fileName = base64_decode($fileName);
}
$fileName = htmlspecialchars($fileName);
$mimeType = htmlspecialchars($_SERVER['HTTP_X_FILE_TYPE']);
$size = intval($_SERVER['HTTP_X_FILE_SIZE']);
$inputStream = fopen('php://input', 'r');
// $outputFilename = $config['upload_dir'] . '/' . $fileName;
$outputFilename = 'gallery' . '/' . $fileName;
$realSize = 0;
$data = '';
if ($inputStream) {
if (! $config['fake']) {
$outputStream = fopen($outputFilename, 'w');
if (! $outputStream) {
_error('Error creating local file');
}
}
while (! feof($inputStream)) {
$bytesWritten = 0;
$data = fread($inputStream, 1024);
if (! $config['fake']) {
$bytesWritten = fwrite($outputStream, $data);
} else {
$bytesWritten = strlen($data);
}
if (false === $bytesWritten) {
_error('Error writing data to file');
}
$realSize += $bytesWritten;
}
if (! $config['fake']) {
fclose($outputStream);
}
} else {
_error('Error reading input');
}
if ($realSize != $size) {
_error('The actual size differs from the declared size in the headers');
}
_log(sprintf("[raw] Uploaded %s, %s, %d byte(s)", $fileName, $mimeType, $realSize));
_response();
However, I am getting an Internal Server 500 Error - Meaning that there was something probably wrong with my php file.
I mainly have two questions:
How do I make the uploadParams work with the FormDataUploader?
How do I write a PHP uploader for an ExtJS Data Uploader?
Got it to work.
The uploadExtJS.php file should look like:
<?php
/**
* Example processing of raw PUT/POST uploaded files.
* File metadata may be sent through appropriate HTTP headers:
* - file name - the 'X-File-Name' proprietary header
* - file size - the standard 'Content-Length' header or the 'X-File-Size' proprietary header
* - file type - the standard 'Content-Type' header or the 'X-File-Type' proprietary header
*
* Raw data are read from the standard input.
* The response should be a JSON encoded string with these items:
* - success (boolean) - if the upload has been successful
* - message (string) - optional message, useful in case of error
*/
// require __DIR__ . '_common.php';
// $config = require __DIR__ . '_config.php';
require_once '_common.php';
$config = require_once '_config.php';
error_reporting(-1);
ini_set('display_errors', 'On');
/*
* You should check these values for XSS or SQL injection.
*/
if (!isset($_SERVER['HTTP_X_FILE_NAME'])) {
_error('Unknown file name');
}
$fileName = $_SERVER['HTTP_X_FILE_NAME'];
if (isset($_SERVER['HTTP_X_FILENAME_ENCODER']) && 'base64' == $_SERVER['HTTP_X_FILENAME_ENCODER']) {
$fileName = base64_decode($fileName);
}
$fileName = htmlspecialchars($fileName);
$mimeType = htmlspecialchars($_SERVER['HTTP_X_FILE_TYPE']);
$size = intval($_SERVER['HTTP_X_FILE_SIZE']);
$inputStream = fopen('php://input', 'r');
$outputFilename = $config['upload_dir'] . '/' . $fileName;
// $outputFilename = 'gallery' . '/' . $fileName;
$realSize = 0;
$data = '';
if ($inputStream) {
if (! $config['fake']) {
$outputStream = fopen($outputFilename, 'w');
if (! $outputStream) {
_error('Error creating local file');
}
}
while (! feof($inputStream)) {
$bytesWritten = 0;
$data = fread($inputStream, 1024);
if (! $config['fake']) {
$bytesWritten = fwrite($outputStream, $data);
} else {
$bytesWritten = strlen($data);
}
if (false === $bytesWritten) {
_error('Error writing data to file');
}
$realSize += $bytesWritten;
}
if (! $config['fake']) {
fclose($outputStream);
}
} else {
_error('Error reading input');
}
if ($realSize != $size) {
_error('The actual size differs from the declared size in the headers');
}
_log(sprintf("[raw] Uploaded %s, %s, %d byte(s)", $fileName, $mimeType, $realSize));
_response(true, "okay");
_common.php looks like:
<?php
function _log($value){
error_log(print_r($value, true));
}
function _response($success = true, $message = 'OK'){
$response = array(
'success' => $success,
'message' => $message
);
echo json_encode($response);
exit();
}
function _error($message){
return _response(false, $message);
}
_config.php should look like:
<?php
return array(
'upload_dir' => 'gallery',
'fake' => false
);
?>
and now I'm working on using a unique name using uniqid() and microtime(), as well as saving the images to a subdirectory (or any folder under your main upload/gallery folder) using the uploadParams() property.
EDIT 1: RENAMING THE UPLOADED FILE
just change this line:
$fileName = htmlspecialchars($fileName);
to:
$fileName = uniqid() . '_' . microtime();
EDIT 3: TO GET THE CUSTOM SUB DIRECTORY FROM YOUR ADDITIONAL PARAMS
First, make sure than when you create your Upload Dialog from your ExtJS web app, you do this:
var uploadPanel = Ext.create('Ext.ux.upload.Panel', {
uploaderOptions : {
url : 'uploadExtJS.php'
},
synchronous : true,
uploadParams : {
ID_1 : ID_1,
ID_2 : ID_2 // you can put waaay more if you want
}
});
and in your uploadExtJS.php, do this (between the part where you define your new file name and the part where you check for input stream)
$fileName = uniqid() . '_' . microtime();
$mimeType = htmlspecialchars($_SERVER['HTTP_X_FILE_TYPE']);
$size = intval($_SERVER['HTTP_X_FILE_SIZE']);
$ID_1 = $_GET['ID_1'];
$ID_2 = $_GET['ID_2'];
$newFilePath = $config['upload_dir'] . '/' . $ID_1 . '/' . $ID_2;
if (!file_exists($newFilePath)) {
mkdir($newFilePath, 0777, true);
}
$inputStream = fopen('php://input', 'r');
$outputFilename = $newFilePath . '/' . $fileName;
$realSize = 0;
$data = '';
As you can see, I defined a $newFilePath variable, checked if it was existing before making it, then uploaded to that directory.
Hope this helps anyone who encounters the issue in the future.

JQuery AJAX File Upload Error 500

So I'm trying to do a file upload using JQuery's AJAX thing, and it keeps giving me the error 500.
$(function() {
$( 'form' ).submit
(
function()
{
$.ajax({
type: 'POST',
url: 'photochallenge/submit.php',
data: new FormData(this),
processData: false,
contentType: false,
success: function(data) {
Materialize.toast(data, 4000);
}
});
return false;
}
);
});
I am also using this PHP code to process the file upload:
<?php
$target_dir = "uploads/";
$target_file = null;
$uploadOk = 1;
$response = "Please choose an image";
// Check if image file is a actual image or fake image
if(isset($_POST["pic"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
$uploadOk = 1;
} else {
$response = "File is not an image.";
$uploadOk = 0;
}
// Check file size
if ($uploadOk == 1 && $_FILES["fileToUpload"]["size"] > 500000) {
$response = "Sorry, your file is too large.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
// if everything is ok, try to upload file
} else {
//find target file
$found = false
$tmp = 0
while(!$found) {
$target_file = $target_dir . $tmp . ".png";
if(file_exists($target_file)) {
$tmp = $tmp + 1;
} else {
$found = true;
}
}
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
$response = "Thank you for your submission!";
shell_exec("python log.py ".$_POST["firstname"]." ".$_POST["lastname"]." ".$target_file);
} else {
$response = "Sorry, there was an error uploading your file.";
}
}
}
echo $response;
?>
Unfortunately, I cannot release the link to where the actual problem is, but hopefully this code is enough to help solve the problem. If any other details are needed, please do not hesitate to let me know.
If you are not using ".htaccess", the issue may be in the shell_exec that may be crashing the application, if you are using something as fast-cgi.
Comment this line and perfom your script:
shell_exec("python log.py ".$_POST["firstname"]." ".$_POST["lastname"]." ".$target_file);
Using comments in PHP:
//shell_exec("python log.py ".$_POST["firstname"]." ".$_POST["lastname"]." ".$target_file);

Categories