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);
Related
I am using easyupload jquery
Src: https://github.com/fater/jquery-easyupload
I am trying to upload files ( images,doc,docx uploaded perfectly) but pdf showing me error but its not explaning the error.
My CODE:
elseif ($type == "upload_file") {
$target_dir = $_SERVER['DOCUMENT_ROOT']."/admin2/uploads/images/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if (file_exists($target_file)) {$data['status'] = "error"; $data['msg'] = $BNL->msg("הקובץ עם השם הזה כבר קיים במערכת.");}
elseif ($_FILES["file"]["size"] > 5000000) {$data['status'] = "error"; $data['msg'] = $BNL->msg("המגבלה של העלאת קובץ היא 5MB");}
elseif($imageFileType != "pdf" && $imageFileType != "doc" && $imageFileType != "docx" ) {$data['status'] = "error"; $data['msg'] = $BNL->msg("הקבצים המותרים הם PDF, DOC, DOCX");}
else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
$data['msg'] = $BNL->msg("הקובץ ". basename( $_FILES["file"]["name"]). " הועלה בהצלחה.", true);
$_SESSION['file'] = basename( $_FILES["file"]["name"]);
} else {
//$data['msg'] = $BNL->msg("סליחה, הייתה בעיה בהעלאת הקובץ.");
$data['msg'] = $_FILES['file']['error']; // Print "1"
}
}
echo json_encode($data);
}
I cant figure it out what the problem I am trying to fix it for two days.
Any one can help me please, thanks in advance.
In this case, we need to check
upload_max_filesize and post_max_size.
http://php.net/manual/en/features.file-upload.php
<?php
try {
if (empty($_FILES)) {
new \Exception('$_FILES array is empty.');
} else {
if (isset($_FILES['file']) && !empty($_FILES['file'])) {
//Check error code
#https://github.com/zendframework/zend-validator/blob/master/src/File/Upload.php#L25
};
}
} catch (Throwable $exception) {
echo $exception->getMessage();
}
https://github.com/zendframework/zend-validator/blob/master/src/File/Upload.php#L25
Read more: $_FILE upload large file gives error 1 even though upload_max_size is bigger than the file size
<?php
include 'model.php';
$rs=new database();
if(isset($_POST["Import"])){
echo $filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
$res=$rs->insert($emapData[0],$emapData[1],$emapData[2],$emapData[3],$emapData[4],$emapData[5]);
$result=mysql_fetch_array($res);
if(! $result )
{
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.\");
window.location = \"result.php?msg=valid\"
</script>";
}
}
fclose($file);
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"result.php?msg=valid\"
</script>";
mysql_close($conn);
}
}
?>
this code only uploads csv file but i want to upload xls too with this code. if possible i want to upload all format of excel . and the rest of code is working fine and also i dont want to change the method.
Download PHPExcel
https://github.com/PHPOffice/PHPExcel
and create this function
function getDataFromExcel($filename)
{
$excel = PHPExcel_IOFactory::load($filename);
$sheet = $excel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$sheetData = $sheet->toArray(null, true, true, true);
return $sheetData;
}
It will return data in array
if you want to know the type of file use this method
function getFileType($key)
{
//Define type
$type = 'unknow';
if(isset($_FILES[$key])) {
$file = $_FILES[$key];
$fileType = $file['type'];
if (strrpos($fileType, 'csv')) {
$type = 'csv';
} else if (($fileType == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') || ($fileType == 'application/vnd.ms-excel')) {
$type = 'excel';
}
}
return $type;
}
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.
I'm testing uploads on 3 files on my desktop test.xlsx, test - Copy.xlsx, and test - Copy (2).xlsx. My PHP script is breaking at the line where my move_uploaded_files statement is. I get the error move_uploaded_file(uploads/test - Copy.xlsx): failed to open stream: No such file or directory. BUT test - Copy (2).xlsx is uploaded when I check my uploads folder. My PHP is as follows:
foreach($_FILES['file']['name'] as $key=>$value){
$fileName = $_FILES['file']['name'][$key];
$fileTmpLoc = $_FILES['file']['tmp_name'][$key];
$fileErrorMsg = $_FILES['file']['error'][$key];
$type = $_FILES['file']['type'][$key];
if(){
//validation
} else{ //if validated
if(move_uploaded_file($fileTmpLoc, 'uploads/'.$fileName)){
//do more stuff
} else{
echo "Upload failed.";
}
}
}
The //do more stuff actually runs once for test - Copy (2).xlsx (the only file uploaded successfully). My JS script is below but I doubt that's the part that's breaking since when I print_r($_FILES) in PHP, all files appear in the output.
var upload = function(event){
var file = document.getElementById('file').files;
var data = new FormData();
for (i=0; i<file.length; i++){
data.append('file[]', file[i]);
}
var request = new XMLHttpRequest();
request.addEventListener('load', completeHandler, false);
request.addEventListener('error', errorHandler, false);
request.addEventListener('abort', abortHandler, false);
request.open('POST', 'php/excel_upload_read.php');
request.send(data);
};
What am I doing wrong?
Looks like you are using the multi-dimensional array in the wrong order. Try this:
foreach($_FILES['file'] as $key=>$value){
$fileName = $_FILES['file'][$key]['name'];
$fileTmpLoc = $_FILES['file'][$key]['tmp_name'];
$fileErrorMsg = $_FILES['file'][$key]['error'];
$type = $_FILES['file'][$key]['type'];
...
}
The problem is the way $_FILES global is structured, it does not let you iterate easily.
You can use this function it s meant to reorganize the data structure
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
Then you can use foreach easily:
if(isset($_FILES['file']['tmp_name'], $_POST)) {
$files = reArrayFiles($_FILES['file']);
foreach ($files as $file) {
$temp = $file['tmp_name'];
$path = 'uploads/'.$file['name'];
if(move_uploaded_file($temp, $path)){
echo 'Upload succesful';
}else{
echo 'failed to upload';
}
}
}else{
echo 'file not uploaded';
}
This function reArrayFiles was posted by someone in the PHP documentation:
http://php.net/manual/en/features.file-upload.multiple.php
I've got a problem with an image upload in AngularJS. I found this question on here: Angularjs - File upload with php
As in the other question I try to use https://github.com/danialfarid/angular-file-upload
My problem is that my image that I try to upload isn't send to my php file.
Here is the code that I use.
PlayerController.js
angular.module('lax').controller('PlayerController', function($scope, $http, $upload) {
$scope.onFileSelect = function($files) {
$scope.message = "";
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
console.log(file);
$scope.upload = $upload.upload({
url: 'php/upload.php',
method: 'POST',
file: file
}).success(function(data, status, headers, config) {
$scope.message = data;
}).error(function(data, status) {
$scope.message = data;
});
}
};
});
HTML
<div ng-show="newplayer.functie == 'update'">
<h3>Profile Pic</h3>
<div>
<input type="file" name="image" id="image" ng-file-select="onFileSelect($files)">
<br/>
<span class="errorMsg">{{ message}}</span>
</div>
</div>
upload.php
<?php
if(isset($_FILES['image'])){
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$extensions = array("jpeg","jpg","png");
if(in_array($file_ext,$extensions )=== false){
$errors[]="image extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size cannot exceed 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"../../Img/PlayerAvatar/".$file_name);
echo $fname . " uploaded file: " . "images/" . $file_name;
}else{
print_r($errors);
}
}
else{
$errors= array();
$errors[]="No image found";
print_r($errors);
}
?>
So the "if(isset($_FILES['image']))" gives false as a result. I'm new to stackoverflow and angularJS so sorry for any noob questions.
I had a problem in my PHP. The problem was with the $_FILES['image'] image should have been file
It should have been:
<?php
if(isset($_FILES['file'])){
$errors= array();
$file_name = $_FILES['file']['name'];
$file_size =$_FILES['file']['size'];
$file_tmp =$_FILES['file']['tmp_name'];
$file_type=$_FILES['file']['type'];
$file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$extensions = array("jpeg","jpg","png");
if(in_array($file_ext,$extensions )=== false){
$errors[]="image extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size cannot exceed 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"PlayerAvatar/".$file_name);
echo " uploaded file: " . "images/" . $file_name;
}else{
print_r($errors);
}
}
else{
$errors= array();
$errors[]="No image found";
print_r($errors);
}
?>