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);
}
// ...
}
Related
I am using the following pair of javascript and php files to get the names of all the image files in a directory.
Javascript
$(document).on("click", "ul#matchListUL li a", function(event){
event.preventDefault();
var matchLst = $(this).attr('href');
var filenames = new Array();
if (matchLst !== null && matchLst !=="") {
$.ajax({
url : "filenames.php",
dataType : "JSON",
type : "POST",
success:function(data) {
console.log(data);
}
});
}
return false;
})
filename.php
$tardir = "mysite.com/projects/" . $seldir . "/" . $match . "/*.jpg" ;
$files = glob($tardir);
$fileName = array();
for ($i=0; $i<count($files); $i++)
{
$num = $files[$i];
$fileName = basename($num, ".jpg");
}
echo json_encode($fileName);
However, this just prints only one file name - essentially the last file in the folder.
How can i get all the filenames and can is save the filenames locally using local storage?
You are doing it wrong, you should do this:
for ($i=0; $i<count($files); $i++)
{
$num = $files[$i];
// [] will add the value to the array
$fileName[] = basename($num, ".jpg");
}
And instead of using a for loop to go through your array, use a foreach loop instead, like this:
foreach($files as $file){
$fileName[] = basename($file, ".jpg");
}
well i have this problem about sending multi data from JS to PHP, i'm using angularJS. the problem is i can't receive any data, i'm a beginner in this stuff like AngularJS.this my my JS part:
var data = {"name":name, "cin":cin, "job":job};
var config = {
params: data,
headers: { 'Content-Type': 'application/json' }
};
$request = "php/readFromDatabase.php";
$http.post($request, config).then(function (response) {
$scope.collectionData = response.data.records;
});
this should be fine and work i have my data as struct (object) the name and cin and job are variables when i click button using angularJS controller this function should be launched and call an PHP file :
<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
$name = $_POST['name'];
i use those information to look for data in database and then i echo them as JSON format for that i want to use $http.get{} so i can call the response.data.records and not to use the $ajax.{}.
the problem is this $_POST['name'] doesn't work;
even this didn't work:
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$name = $request->name;
As i said, i'm new here so plz tell me what i'm doing wrong because i didn't find anything that can help me, i tied everything i have found in internet.
hope if someone can help me and thank you in advance.
Edit :
this is my JS file:
app.controller('shearch_data', function ($scope, $http) {
$scope.ShearchFunction = function () {
var name = " ";
if ($('#toggle_name').prop('checked') == true)
name = $('#inputName').val();
var cin = " ";
if ($('#toggle_cin').prop('checked') == true)
cin = $('#inputCIN').val();
var job = " ";
if ($('#toggle_job').prop('checked') == true)
job = $('#inputJob').val();
var data = {'name': "ffss", 'cin': cin, 'job': job};
var url = "php/readFromDatabase.php";
$http.post(url, data).then(function (response) {
$scope.collectionData = response.data.records;
}).catch(function (err) {
alert('something went wrong')
});
};
});
my PHP :
<?php
header("Access-Control-Allow-Origin: *");
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$name = $request->name;
$cin = $request->cin;
$job = $request->job;
$output = "";
$output .='{"Name":"'.$name.'",';
$output .='"Job":"'.$job.'",';
$output .='"Cin":"'.$cin.'"}';
$output = '{"records":[' . $output . ']}';
echo($output);
this is what i'm trying to do for test, send data from JS to PHP using http.post then i receive it as json, it's jsut for test for now.
Arguments and config are wrong for $http.post( url, data, config)
Remove params from config, those are for GET url query string params
EDIT: if all you are setting is the 'Content-Type header you don't need a config....application/json is the default
var config = {
headers: { 'Content-Type': 'application/json' }
};
var url = "php/readFromDatabase.php";
$http.post(url, data, config).then(function (response) {
$scope.collectionData = response.data.records;
}).catch(function(err){
alert('Ooops...something went wrong')
});
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
EDIT: I solved it. I wrote:
$scope.result = data
In the success-area.
I have a form that you can upload files. I'm using angular-file-upload 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, and print it out at the site, but I don't now how to bind the file to the $scope.
Here is my controler:
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);
});
}
});
Here is my PHP:
$filename = $_FILES['file']['tmp_name'];
if(($handle = fopen($filename, "r")) !== FALSE) {
while(($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br/></p>\n";
$row++;
for($c = 0; $c < $num; $c++) {
echo $data[$c] . "<br/>\n";
}
}
fclose($handle);
}
And here is my HTML:
<div ng-controller="Marketing">
<form class="well form-search" enctype="multipart/form-data">
<input type="file" name="image" ng-file-select="onFileSelect($files)" >
</form>
<pre ng-model="result">
{{result}}
</pre>
</div>
As you can see, I want to bind the content to the $scope.result.
Since you already have your files in the app, you just have to bind them to the $scope
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) {
// This is the file you've just successfully uploaded
$scope.file = file
});
}
});
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);
}
?>