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
});
}
});
Related
I need to get an array $data from the backend to the frontend in order to organize it for viewing. I can only find examples using jQuery Ajax.
<!DOCTYPE html>
<html>
<style>
.table_class{
display:none;
}
</style>
<script>
async function uploadFile() {
let formData = new FormData();
formData.append("file", fileupload.files[0]);
console.log(formData);
await fetch('file_ingest.php', {
method: "POST",
body: formData,
});
var test = document.getElementById("test");
test.innerText = ('The file has been uploaded successfully.');
//var returned_vals = JSON.parse(formData.responseText);
//console.log(returned_vals);
}
</script>
<body>
<input id="fileupload" type="file" name="fileupload" />
<button id="upload-button" onclick="uploadFile()"> Upload </button>
<p id = "test"></p>
</body>
</html>
I need to get an array $data from the backend to the frontend in order to organize it for viewing. I can only find examples using jQuery Ajax.
<?php
set_time_limit(120);
/* Get the name of the uploaded file */
$filename = $_FILES['file']['name'];
/* Choose where to save the uploaded file */
$location = "uploads/".$filename;
if ( move_uploaded_file($_FILES['file']['tmp_name'], $location) ) {
echo 'Success';
} else {
echo 'Failure';
$CSVfp = fopen("uploads/${filename}", "r");
if($CSVfp !== FALSE) {
while(! feoF($CSVfp)) {
$data = fgetcsv ($CSVfp, 1000, ",");
print json_encode($data);
//echo $data;
}
}
fclose($CSVfp);
<?php
set_time_limit(120); // if you need this you may have other problems
/* Get the name of the uploaded file */
$filename = $_FILES['file']['name'];
/* Choose where to save the uploaded file */
$location = "uploads/".$filename;
$response = [];
/* Save the uploaded file to the local filesystem */
if ( move_uploaded_file($_FILES['file']['tmp_name'], $location) ) {
$response['status'] = 'Files Save Success';
// read the file here, if it failed the upload and move
// there is no point trying to read it
if (($fp = fopen($location, "r")) !== FALSE) {
while (($data = fgetcsv($fp, 1000, ",")) !== FALSE) {
$response['data'][] = $data
}
fclose($fp);
}
} else {
$response['status'] = 'File Save Failure';
}
// now you can return either an error or a success and data
echo json_encode($response);
Now you need to checnge the javascript to look for the status in the right place and unload the row data from the the right place
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.
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);
}
// ...
}
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);
}
?>
I have written a JS script, a CodeIgniter controller and a html form to upload the files via jquery ajax.
It does not uploads files. I have solved all the issues but this last one was beyond my ability.
The AJAX request completes successfully but the codeigniter upload class erros "you did not select a file to upload."
Here is my HTML file and button:
<input type="file" class="form-file" id="file" multiple name="file[]" />
<input value='add picture' type="button" name="file-submit" class="form-submit" id='file-submit'/>
And here is the CodeIgniter controller responsible to upload the files:
class Upload extends CI_Controller
{
function pictures ()
{
$config['upload_path'] = '../uploads/categories/';
$this->load->library("upload", $config);
if(!$this->upload->do_upload("file"))
{
echo $this->upload->display_errors();
}
else
{
echo "Thanks";
}
}
}
And here is the jQuery AJAX script:
$(document).ready(function()
{
var files; // main variable to keep images into it
// lets put the files into a variable
var file_field = $('input[type=file]');
file_field.on('change', appendFiles);
function appendFiles (event)
{
files = event.target.files;
console.log(files);
}
// now attach click event to upload
$('#file-submit').on('click',
function uploadFiles (event)
{
event.preventDefault();
// create a form data
var data = new FormData();
$.each(files, function (key, val)
{
data.append(key, val);
// now all the contents of the files have been assigned to a form-data variable
});
// begin the AJAX
$.ajax({
url : base_path("upload/pictures/"),
data: data,
cache:false,
processData: false,
contentType: false,
success: function(msg)
{
console.log(msg);
},
error : function()
{
console.log("Error");
}
});
});
// form_file
});
Use jQueryFileUpload Plugin:
Download JS: http://yourcareeracademy.com/yca/assets/plugins/ajaxfileupload/ajaxfileupload.js
-view-
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="<?php echo base_url('js/ajaxfileupload.js')?>"></script>
</head>
<body>
<h1>Upload File</h1>
<form method="post" action="" id="upload_file">
<label for="title">Title</label>
<input type="text" name="title" id="title" value="" />
<label for="userfile">File</label>
<input type="file" name="userfile" id="userfile" size="20" />
<input type="submit" name="submit" id="submit" />
</form>
<h2>Files</h2>
<div id="files"></div>
</body>
</html>
--script in page--
$(function() {
$('#upload_file').submit(function(e) {
e.preventDefault();
$.ajaxFileUpload({
url :'./upload/upload_file/',
secureuri :false,
fileElementId :'userfile',
dataType : 'json',
data : {
'title' : $('#title').val()
},
success : function (data, status)
{
if(data.status != 'error')
{
$('#files').html('<p>Reloading files...</p>');
refresh_files();
$('#title').val('');
}
alert(data.msg);
}
});
return false;
});
});
-controller-
public function upload_file()
{
$status = "";
$msg = "";
$file_element_name = 'userfile';
if (empty($_POST['title']))
{
$status = "error";
$msg = "Please enter a title";
}
if ($status != "error")
{
$config['upload_path'] = './files/';
$config['allowed_types'] = 'gif|jpg|png|doc|txt';
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload($file_element_name))
{
$status = 'error';
$msg = $this->upload->display_errors('', '');
}
else
{
$data = $this->upload->data();
$file_id = $this->files_model->insert_file($data['file_name'], $_POST['title']);
if($file_id)
{
$status = "success";
$msg = "File successfully uploaded";
}
else
{
unlink($data['full_path']);
$status = "error";
$msg = "Something went wrong when saving the file, please try again.";
}
}
#unlink($_FILES[$file_element_name]);
}
echo json_encode(array('status' => $status, 'msg' => $msg));
}