Laravel file is not uploded - php

I try to make a page to upload some files to server side. But it does not work.
// **Here my upload.blade.php**
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Laravel Multiple Files Upload Using Dropzone with - CodingDriver</title>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.0/min/dropzone.min.css">
</head>
<style>
.alert-message {
color: red;
}
</style>
<body>
<div class="container">
<h2 style="margin-top: 12px;" class="alert alert-success">Laravel Multiple Files Upload Using Dropzone -
<a href="https://www.codingdriver.com" target="_blank" >CodingDriver</a>
</h2>
<div class="row" style="clear: both;margin-top: 18px;">
<div class="col-12">
<div class="dropzone" id="file-dropzone"></div>
</div>
</div>
</div>
</body>
</html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.7.0/min/dropzone.min.js"></script>
<script>
Dropzone.options.fileDropzone = {
url: 'upload/classification',
acceptedFiles: ".jpeg,.jpg,.png,.gif",
addRemoveLinks: true,
maxFilesize: 8,
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}"
},
removedfile: function(file)
{
var name = file.upload.filename;
$.ajax({
type: 'POST',
url: 'file.remove',
data: { "_token": "{{ csrf_token() }}", name: name},
success: function (data){
console.log("File has been successfully removed!!");
},
error: function(e) {
console.log(e);
}});
var fileRef;
return (fileRef = file.previewElement) != null ?
fileRef.parentNode.removeChild(file.previewElement) : void 0;
},
success: function (file, response) {
console.log(response);
},
}
</script>
// **my web.php**
Route::get('upload',function(){
return view('upload');
});
Route::post('upload/classification', [imageClassificationController::class, 'uploadDataset']);
<?php
// my imageClassificationController.php
namespace App\Http\Controllers;
use App\Models\imageClassificationModel;
use Illuminate\Http\Request;
use App\Models\fileTransferModel;
use Auth;
config('projectConfigs.pathConfigs');
class imageClassificationController extends Controller
{
public function uploadDataset()
{
try{
$file = request()->file();
//echo 'File Name: '.$file->getClientOriginalName();
//return __DIR__;
//$fileName= $file->getClientOriginalName();
//return $file;
$file->move(__USERFOLDERS__.DIRECTORY_SEPARATOR.Auth::user('foldername').DIRECTORY_SEPARATOR.'image-classification'.DIRECTORY_SEPARATOR.'datasets',$file);
return $file->getClientOriginalName();
}
catch(Exception $e){
return 'test'.$e;
}
}
}
These codes return 500 internal server error. But if I return $file, it returns javascript file object. I don't know why I cant save the uploaded file. Also getClientOriginalName returns 500 internal server error. And at last, try-catch also returns 500 internal server error.
Thanks for your helps...

You've got to add the input name to the request file function, and use the Laravel File move functionality:
public function uploadDataset()
{
try{
$file = request()->file('file'); // the input name attribute
$file->move(__USERFOLDERS__.DIRECTORY_SEPARATOR.Auth::user('foldername').DIRECTORY_SEPARATOR.'image-classification'.DIRECTORY_SEPARATOR.'datasets'.DIRECTORY_SEPARATOR, $file->getClientOriginalName());
return $file->getClientOriginalName();
}
catch(Exception $e){
return 'test'.$e;
}
}

Related

Why the AJAX response is not returned from PHP side

I am trying to get the PHP threads progress via AJAX, but the strange think I am facing right now is that any code before startPool() method can be seen in the AJAX response but not after it, would you explain to me why this is happening?
AjaxIndex.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Source code generated using layoutit.com">
<meta name="author" content="LayoutIt!">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<link href="css/gijgo.min.css" rel="stylesheet" type="text/css" />
<style>
.error {
border: 5px solid red !important;
}
.download-link {
color: #26c605;
}
.download-error {
color: #f20404;
}
</style>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-4">
<form id="county-form" role="form" autocomplete="off">
<div class="form-group">
<label for="courtHouse">
Choose an action to scrap:
</label>
<select id="courtHouse" name="get-data" class="form-control">
<option value="none"></option>
<option value="all" selected="selected">Scrap.</option>
<option value="force">Force scrap.</option>
</select>
</div>
<button id="scrape-button" type="button" class="btn btn-primary">
Scrap now
</button>
<p id="result"></p>
</form>
</div>
</div>
</div>
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/gijgo.min.js" type="text/javascript"></script>
<script src="js/scripts.js"></script>
<script>
$(document).ready(function() {
let result_label = $("p#result");
$("button#scrape-button").on('click', function(e){
e.preventDefault();
result_label.removeClass('download-error').html('');
if($('#courtHouse option:selected').text() === '') {
$("#courtHouse").css("border", "2px solid red");
$("#courtHouse").focus();
return;
}
$("#courtHouse").css("border", "0.916667px solid rgba(0, 0, 0, 0.15)");
$("#courtHouse").focus();
result_label.html('<b>Please don\'t close the browser until the link appears here.</b>');
const formData2 = $("#county-form").serialize();
let last_response = '';
$.ajax({
//url: "testAJAX.php",
url: "AjaxThread.php",
method: 'POST',
data: formData2,
dataType: 'text',
//contentType: 'application/json',
encode: true,
xhrFields: {
onprogress: function(e) {
let response = e.target.response.replace(/\n/g, '').split("|").slice(0, -1).pop();
//console.log('response split: ', e.target.response.replace(/\n/g, '').split("|").slice(0, -1));
console.log('response pop: ', response);
//console.log('response pop: ', JSON.parse(response).replace(/\n/g, ''));
}
},
success: function (result, status, xhr) {
console.log('success step');
console.log(result.status);
if(result.status === 'success') {
result_label.html(result.data);
}
else {
result_label.removeClass('download-link').addClass('download-error').html(result.data);
}
},
error: function(request, status, error) {
result_label.removeClass('download-link').addClass('download-error').html('Internal error, please contact the support.');
console.log('error step');
//console.log(JSON.stringify(request));
console.log(request);
console.log(status);
console.log(error);
}
});
});
});
</script>
</body>
</html>
AjaxThread.php:
<?php
require_once __DIR__ . '/vendor/autoload.php';
use \ByJG\PHPThread\ThreadPool as ScrapperPool;
try {
$scrapper_pool = new ScrapperPool();
for($i = 0; $i < 10; ++$i) {
$rfc_scrapper = new ScrapperThread($i);
$scrap = function(ScrapperThread $instance) {
return $instance->scrap();
};
$scrapper_pool->queueWorker($scrap, [$rfc_scrapper]);
}
$scrapper_pool->startPool();
$scrapper_pool->waitWorkers();
// Get results
file_put_contents('AjaxThreadCount', count($scrapper_pool->getThreads())); //
foreach($scrapper_pool->getThreads() as $worker) {
echo($scrapper_pool->getThreadResult($worker));
}
}
catch(Exception $e) {
echo $e->getMessage();
}
?>
Check if this helps
<?php
require_once __DIR__ . '/vendor/autoload.php';
use \ByJG\PHPThread\ThreadPool as ScrapperPool;
try {
$scrapper_pool = new ScrapperPool();
for($i = 0; $i < 10; ++$i) {
$rfc_scrapper = new ScrapperThread($i);
$scrap = function(ScrapperThread $instance) {
return $instance->scrap();
};
$scrapper_pool->queueWorker($scrap, [$rfc_scrapper]);
}
$scrapper_pool->startPool();
$scrapper_pool->waitWorkers();
$result_getThreads = $scrapper_pool->getThreads();
// Get results
file_put_contents('AjaxThreadCount', count($result_getThreads)); //
if($result_getThreads){
foreach($result_getThreads as $worker) {
echo($scrapper_pool->getThreadResult($worker));
}
}else{
echo 'Something went wrong';
}
}
catch(Exception $e) {
echo $e->getMessage();
}
?>
Important Apache webserver information
Try to run AjaxThread.php through command line and see if it works with (exit() in ForkHandler.php). Because you do an ajax request I suppose you run this through an apache webserver. In this case the exit() does not work, you should use instead:
posix_kill(getmypid(), SIGKILL);
Change this line:
for($i = 0; $i < 10; ++$i) {
to
for($i = 0; $i < 10; $i++) {

AngularJS errorcallBack

I'm having some difficulty with AngularJS. Any constructive help is greatly appreciated.
This is the Angular code I'm working with
app.controller('customersCtrl', function($scope, $http) {
$scope.element = function(num){
var element_id = num;//num;
$http.get("customers.php",{params:{"id":element_id}}).then(function (response) {
$scope.myData = response.data;
}
,function errorCallback(response){
$scope.e=response.data;
console.log(e);
});
};
});
And here is my php code I'm using. All this does is return the 401 code. The section works as I can return it in a console log.
http_response_code(401);
$message = http_response_code()." No data found";
header('Content-Type: application/json');
echo json_encode($message);
Here is my HTML code
<!DOCTYPE html>
<html>
<head>
<title>page2</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="css.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> </script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-route.js"></script>
<script src = "javascript.js"></script>
</head>
<body ng-app="input">
<div ng-controller="customersCtrl">
<h1>Click on the contact name for company and location</h1>
<br>
<button ng-click="element(0)">Bob</button>
<button ng-click="element(1)">Jim</button>
<button ng-click="element(2)">Kim</button>
<br>
<br>
<ul>
<li ng-repeat="x in myData">
{{x}}
</li>
</ul>
<div ng-show="error != null">
<p>{{e.error}}</p>
</div>
</div>
View full list
</body>
</html>
I'm having a problem displaying the 401 message in the HTML page. What is a good way of doing this? The code will return the message but only as a console log. I need it in a HTML page. I'm quite confused on this one as I've tried multiple ways and none of them are working. Any help would be greatly appreciated
Thank you in advance!!!
Hey Man try that below:
$scope.e = '';
$scope.myData = [];
$scope.element = function(element_id){
$http({
method: 'GET',
url: "customers.php?id=" + element_id,
headers: {
'Content-Type': 'application/json'
}
})
.then(
function successCallback(response) {
$scope.myData = response.data;
callback(response);
},
function errorCallback(response) {
$scope.e = response.data;
callback(response);
}
);
}
Check on browser the network, and if no work, plz upload the network with log to "customers.php"
Best Wishes

Get data using jQuery ajax method in codeigniter

Below is my view:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="<?php echo base_url("assets/css/bootstrap.min.css"); ?>">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">
<script src="<?php echo base_url("plugins/jQuery/jQuery-2.2.0.min.js"); ?>"></script>
<script type="text/javascript" charset="utf-8">
function waitForMsg1() {
$.ajax({//Ajax method to get data from Message Controller
type: "GET",
url: "<?php echo base_url('index.php/message/messageCount'); ?>",
async: true,
cache: false,
timeout: 50000,
success: function (data) {
addmsg("new", data);
setTimeout(waitForMsg1, 1000);
},
});
};
$(document).ready(function () {
waitForMsg1();
});
function addmsg(type, count) {
$('#badge').html(count); //selecting the element to display inside the badge
}
</script>
</head>
<header>
<a href="#"><span><div id="bounce"><i class="fa fa-envelope ">
<span class="badge" id="badge" style="background-color:red;margin:-25px 0 0 -5px;">
</span></i></div></span></a>
</header>
Below is the Controller:
<?php
class Message extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('MessageDb');
$this->load->model('UserDb');
$this->load->model('EmployeeDb');
}
public function messageCount()
{
echo '12345'; //This is the dummy value.
}
}
?>
I want to display the count from Message controller into the view, it is not working. I tried a lot but not able to rectify the problem. How this can be done?

How to Hide Text Using PHP or jQuery

I have a script code to upload photos on imgur using AJAX. But I can not hide the Client-ID of the public.
I think I need to use PHP to do that use this code:
<?php $idClient = "abc12abc12abc";
echo $idClient ;
?>
But it turned Client-ID is still visible when in view its source code.
Here's the full code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Imgur Upload Test</title>
<style>
#image_preview, #image_preview_2 {
max-width: 200px;
}
</style>
</head>
<body>
<h1>Imgur Upload Test</h1>
<input type="file" id="image_selector" />
<div id="image_preview"></div>
<h2>Image On Imgur:</h2>
<div id="image_preview_2"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$("#image_selector").change(function() {
var reader = new FileReader();
reader.onload = function(e) {
var data = e.target.result.substr(e.target.result.indexOf(",") + 1, e.target.result.length);
$("#image_preview").html("<img src='" + e.target.result + "' />");
$.ajax({
url: 'https://api.imgur.com/3/image',
headers: {
'Authorization': 'Client-ID <?php $idClient = "abc12abc12abc";
echo $idClient ;?>'
},
type: 'POST',
data: {
'image': data,
'type': 'base64'
},
success: function(response) {
$("#image_preview_2").html("<img src='" + response.data.link + "' />");
}, error: function() {
alert("Error while uploading...");
}
});
};
reader.readAsDataURL(this.files[0]);
});
</script>
</body>
</html>
What's the solution?

Session preservation

I read all other question but nothing really helped.
I have one page with display and other php files supporting it but when I pass a POST and make a $_SESSION['view'] out of it with another POST request but not same one the $_SESSION['view'] is gone.
So in practic when user change view from four months (default) to one month and then click NEXT view gets back to four months.
Display Page
<?php
session_start();
$dateb = (new DateTime())->getTimestamp();
$_SESSION['usrdate'] = $dateb;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<link href="site.css" type="text/css" rel="stylesheet">
<script>
$(document).ready(function () {
$("#four").click(function () {
var jqXHR = $.ajax({
type: "POST",
url: "switcher.php",
data: {
view: "four"
},
success: function (html) {
$("#loadplace").html(html);
}
});
return jqXHR.responseText;
});
$("#one").click(function () {
var jqXHR = $.ajax({
type: "POST",
url: "switcher.php",
data: {
view: "one"
},
success: function (html) {
$("#loadplace").html(html);
}
});
return jqXHR.responseText;
});
$("#next").click(function () {
var jqXHR = $.ajax({
type: "POST",
url: "switcher.php",
data: {
toggle: "next"
},
success: function (html) {
$("#loadplace").html(html);
}
});
return jqXHR.responseText;
});
});
</script>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div id="nav"></div>
<div id="loginform"><?php
/*require "navigation.php";*/
if (!isset($_SESSION['id'])) {
include "logon.php";
} else {
echo "<a href='logoff.php'>Logout</a>";
}
?>
</div>
<div id="loadplace">
<?php
if (isset($_SESSION['id'])) {
include "switcher.php";
}
?>
</div>
<div id="tog"><button type="button" id="prev">Prev</button>
<button type="button" id="next">Next</button></div><br/><br/>
<div id="view"><button type="button" id="four">Four</button>
<button type="button" id="one">One</button></div>
</body>
</html>
Script
<?php
session_start();
$_SESSION['view'] = $_POST["view"];
$_SESSION['toggle']= $_POST["toggle"];
$tog = $_SESSION["toggle"];
if ($_SESSION['view'] == "four") {
include_once "four_m.php";
} elseif ($_SESSION['view'] == "one") {
include "calendar.php";
} elseif ($_SESSION['view'] == "week") {
include "week.php";
} elseif ($_SESSION['view'] == "day") {
include "day.php";
} else {
include "four_m.php";
}
?>

Categories