AngularJS Image upload using php - javascript

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

Related

jquery easyupload plugin not uploading pdf files

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

image not displaying in my form in php

I am having issues displaying image on the website i am developing. It a website that users can change their profile picture, as well as their basic profile information. bellow is my sample code.
profile.php
<?php
$studpix=$row_rsp['pix'];
$propix='<img class=
"profile-user-img img-responsive img-circle" src="...
/Student /imageupload/blank.png"
alt="profile picture">';
if($propix!=NULL)
{
$propix='<img class="profile-user-img
img-responsive img-circle" src="Student/imageupload/'.$studpix.'"
alt="profile picture">';
};
$profile_pic_btn =
' Profile pics';
$avatar_form = '<form id="avatar_form"
enctype="multipart/form-data" method="post" action="photoup.php">';
$avatar_form .= '<h4>Change your picture</h4>';
$avatar_form .= '<input type="file" name="avatar" required>';
$avatar_form .= '<p><input type="submit" value="Upload"></p>';
$avatar_form .= '</form>';
?>
<?php echo $propix?><?
php echo $avatar_form?><?php echo $profile_pic_btn;?>
//other codes goes here
imageupload.php
<?php
if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]
["tmp_name"] != ""){
$fileName = $_FILES["avatar"]["name"];
$fileTmpLoc = $_FILES["avatar"]["tmp_name"];
$fileType = $_FILES["avatar"]["type"];
$fileSize = $_FILES["avatar"]["size"];
$fileErrorMsg = $_FILES["avatar"]["error"];
$kaboom = explode(".", $fileName);
$fileExt = end($kaboom);
list($width, $height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10){
echo "ERROR: That image has no dimensions";
exit();
}
$db_file_name = rand(100000000000,999999999999).".".$fileExt;
if($fileSize > 1048576) {
echo "ERROR: Your image file was larger than 1mb";
exit();
} else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) {
echo "ERROR: Your image file was not jpg, gif or png type";
exit();
} else if ($fileErrorMsg == 1) {
echo "ERROR: An unknown error occurred";
exit();
}
$sql = "SELECT pix FROM studentdetails WHERE email='%s'";
$query = mysqli_query($myconn, $sql);
$row = mysqli_fetch_row($query);
$avatar = $row[0];
if($avatar != ""){
$picurl = "../Student/imageupload/$avatar";
if (file_exists($picurl)) { unlink($picurl); }
}
$moveResult = move_uploaded_file(
$fileTmpLoc, "../Student /imageupload /$db_file_name");
if ($moveResult != true) {
echo "ERROR: File upload failed";
exit();
}
include_once("../image_resize.php");
$target_file = "../Student/imageupload/$db_file_name";
$resized_file = "../Student/imageupload/$db_file_name";
$wmax = 200;
$hmax = 300;
img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
$sql = "UPDATE studendetails SET pix='%s' WHERE email='%s' LIMIT 1";
$query = mysqli_query($myconn, $sql);
mysqli_close($myconn);
header("location: profile.php");
exit();
}
?>
Your help will be appreciated.
Try to debug your code step by step.
1. Check whether the file gets uploaded correctly and to the correct folder.
2. Check whether the data is updated correctly in the database.
3. Try to open the file by URL directly in the browser.
4. Check whether your HTML code is outputted correctly on the webpage and debug the outputted source code.
5. Make sure that your HTML code works properly.
There may be more steps to take, but this might give you some direction.

How to upload multiple documents into project folder using Angular.js and PHP

I need to store different types of documents inside the project folder in single button click using Angular.js and PHP. I am explaining my code below.
var fileData={'image':file,'regdoc':regDocs,'compRegDoc':compRegDocs};
$scope.upload=Upload.upload({
url: 'php/uploadAll.php',
method:'POST',
file: fileData
}).success(function(data, status, headers, config) {
console.log('file',data);
}).error(function(data, status) {
console.log('err file',data);
})
uploadALL.php:
<?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){
header("HTTP/1.0 401 Unauthorized");
$errors[]="image extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
header("HTTP/1.0 401 Unauthorized");
$errors[]='File size cannot exceed 2 MB';
}
if(empty($errors)==true){
//$today=('date')(new Date(),'yyyy-MM-dd HH:mm:ss');
move_uploaded_file($file_tmp,"../upload/".$file_name);
echo " uploaded file: " . "upload/" . $file_name;
}else{
print_r($errors);
}
}
else{
$errors= array();
header("HTTP/1.0 401 Unauthorized");
$errors[]="No image found";
print_r($errors);
}
?>
Here I have one image and the other two are .pdf/docx type files. When the user clicks the submit button these 3 files should be stored inside upload folder.
// use this code in php page...
it's used to upload all file
if(isset($_POST['submit'])!=""){
$name=$_FILES['file']['name'];
$size=$_FILES['file']['size'];
$type=$_FILES['file']['type'];
$temp=$_FILES['file']['tmp_name'];
$caption1=$_POST['caption'];
$link=$_POST['link'];
move_uploaded_file($temp,"upload/".$name);
}

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

Return the uploaded file contents as JSON

I'm using angularjs to upload files. Im using this model that I've found at github:
https://github.com/danialfarid/angular-file-upload
The upload works perfect. However, after I've uploaded the file, I want to return the file contents as JSON, and then iterate of the JSON-object with Angular. But I don't know how to do this.
Here is my code:
$filename = $_FILES['file']['tmp_name'];
$csv = array_map('str_getcsv', file($filename));
foreach($csv as $c)
{
echo str_replace(array('"', ';'), ' ', $c[0]) . "\n";
}
//Return as JSON here? HOW?
Here is my controller:
as.controller('Marketing', function($scope, $http, $upload)
{
$scope.onFileSelect = function($files) {
var file = $files[0];
if (file.type.indexOf('image') == -1) {
$scope.error = 'image extension not allowed, please choose a JPEG or PNG file.'
}
if (file.size > 2097152){
$scope.error ='File size cannot exceed 2 MB';
}
$scope.upload = $upload.upload({
url: 'partials/result.php',
data: {},
file: file,
}).success(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
$scope.result = data;
});
}
});
I want the data to be and JSON-object. How can I accomplish this? When I try json_encode with PHP, it does not work.
Anyone who can help me with this?
I believe this is what you're looking for
if(isset($_FILES["file"])){
$fname = $_FILES['file']['tmp_name'];
// ...
if(move_uploaded_file($fname, "uploads/" . $fname)){
// this way
$csv = file_get_contents($fname);
$array = array_map("str_getcsv", explode("\n", $csv));
echo json_encode($array);
// or this way; have in mind delimiter
$row = str_getcsv($csv, "\n");
$length = count($row);
for($i = 0; $i < $length; $i++){
$data = str_getcsv($row[$i], ";");
$array[] = $data;
}
echo json_encode($array);
}
// ...
}

Categories