Download txt file with laravel and axios - laravel

Hello there
Hope you will be doing good.I want to download txt file generated on the fly from the controller of laravel i have search alot but could not find any solution.Please help out i will be very thankful.
Blade code with axios request
submitHandler:function(form,e){
var btn=document.querySelector("#BtnSubmit");
btn.style.display="none";var img=document.createElement("img");
img.setAttribute("src",base_url+'front/images/loading.gif');
var loader=document.querySelector("#loader");loader.appendChild(img);
var url="<?php echo route('database.export-txtProcess');?>";
var cur_url="<?php echo route('database.export-txt');?>";
//var tblExportSelect = $("#tblExportSelect").val();
var pushArray = [];
$.each($("#tblExportSelect option:selected"), function(){
pushArray.push($(this).data("id"));
});
var data = new FormData();
data.append('tblExportSelect',pushArray);
//$("#tblExportSelect").val(selected);
axios({
method: 'POST',
url: url,
data: data,
})
.then(function(res){
console.log(res);
})
e.preventDefault();
}
});
Controller Method
public function exportTxtProcess(Request $request){
/*dd($request->tblExportSelect);*/
$tables = explode(",", $request->tblExportSelect);
$destinationPath = public_path('/');
$result;
foreach ($tables as $table) {
$outputs = DB::select("SELECT * FROM $table");
$today = date("Y-m-d");
$fileName = $table."-".$today;
$fp = fopen($destinationPath . "$fileName.txt","wb");
foreach ($outputs as $output) {
$output = (array)$output;
#array_shift($output);
$removeUserId = #$output['user_id'];
$created_at = #$output['created_at'];
$updated_at = #$output['updated_at'];
if (($key = array_search($removeUserId, $output)) !== false) {
unset($output[$key]);
}
if (($key1 = array_search($created_at, $output))) {
unset($output[$key1]);
}
if (($key2 = array_search($updated_at, $output))) {
unset($output[$key2]);
}
if (is_null($created_at) OR $created_at == '') {
unset($output['created_at']);
}
if (is_null($updated_at) OR $updated_at == '') {
unset($output['updated_at']);
}
$netResult = $this->getTableFields($table,$output);
fwrite($fp,$netResult);
}
$result = fclose($fp);
}
/*$arr = array(['Good' => true,'message' => 'Data has been successfully imported.'], 200);
echo json_encode($arr);*/
if ($result) {
$pathToFile = $destinationPath . "$fileName.txt";
$downloaded = response()->download($pathToFile)->deleteFileAfterSend();
}
}
I want to download when txt file which is created as above but instead of download it streaming in the console.
Thank in advance

You have to pass the headers. Most importantly you are not returning the reponse.
$headers = [
'Content-type' => 'text/plain',
'Content-Disposition' => sprintf('attachment; filename="%s"', $fileName),
'Content-Length' => sizeof($content)
];
return response()->download($pathToFile, $fileName,$headers)->deleteFileAfterSend();

Related

Call to undefined function GuzzleHttp\\Psr7\\build_query()

I have searched online but could not get a solution. I know I have done some small mistakes. I generated my code with openapi-generator. I had a directory at nova-components root named as RegistroImprese I made another directory SevenData and moved all RegistroImprese into this new directory. I have gone through quite a lot of problems but fixed them. Until then my code was working fine. But now it's throwing an exception that query_build is undefined but this same function was working fine earlier. Nothing has helped me. Any help would be appreciated.
public function apiRegistroImpresePostRequest($request = null)
{
$resourcePath = '/api/RegistroImprese';
$formParams = [];
$queryParams = [];
$headerParams = [];
$httpBody = '';
$multipart = false;
if ($multipart) {
$headers = $this->headerSelector->selectHeadersForMultipart(
['application/json']
);
} else {
$headers = $this->headerSelector->selectHeaders(
['application/json'],
['application/json-patch+json', 'application/json', 'text/json', 'application/_*+json']
);
}
// for model (json/xml)
if (isset($request)) {
if ($headers['Content-Type'] === 'application/json') {
$httpBody = \GuzzleHttp\json_encode(ObjectSerializer::sanitizeForSerialization($request));
} else {
$httpBody = $request;
}
} elseif (count($formParams) > 0) {
if ($multipart) {
$multipartContents = [];
foreach ($formParams as $formParamName => $formParamValue) {
$formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
foreach ($formParamValueItems as $formParamValueItem) {
$multipartContents[] = [
'name' => $formParamName,
'contents' => $formParamValueItem
];
}
}
// for HTTP post (form)
$httpBody = new MultipartStream($multipartContents);
} elseif ($headers['Content-Type'] === 'application/json') {
$httpBody = \GuzzleHttp\json_encode($formParams);
} else {
// for HTTP post (form)
$httpBody = \GuzzleHttp\Psr7\build_query($formParams);
}
}
$defaultHeaders = [];
if ($this->config->getUserAgent()) {
$defaultHeaders['User-Agent'] = $this->config->getUserAgent();
}
$headers = array_merge(
$defaultHeaders,
$headerParams,
$headers
);
$query = \GuzzleHttp\Psr7\build_query($queryParams);
return new Request(
'POST',
$this->config->getHost() . $resourcePath . ($query ? "?{$query}" : ''),
$headers,
$httpBody
);
}
This problem was solved by using Query::build. After Guzzle 7.2 build_query()was deprecated.

How to get files as url from laravel storage folder and convert them as base 64 in vuejs?

i'm trying to get files from storage folder and converting them into base64 in vue.js. i'm using below method, But it seems not working.
public function getImages()
{
$filesToReturn = [];
$files = File::files(storage_path() . "/app/record_keeper");
foreach ($files as $file) {
array_push($filesToReturn, $file->getRealPath());
}
return response()->json(['files' => $filesToReturn], $this->response_status_code, 200);
}
returned file urls
{"files":["/home/Project/vue_image_previewer/storage/app/record_keeper/1.jpeg","/home/Project/vue_image_previewer/storage/app/record_keeper/2.jpeg"]}
in vue js
data() {
return {
imageUrls: [],
images: [],
img_id: 0,
currentIndex: 0,
savedImages: [],
}
},
methods: {
async getAllImagesById() {
await this.axios.get('/aaa-get-images').then(response => {
this.savedImages = response.data.data;
self.savedImages.forEach(function (url) {
this.toDataUrl(url);
});
},
toDataUrl(url) {
let self = this;
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
self.imageUrls.push({
file: reader.result,
});
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
}
where is the problem?
Thank you!
here is the result.
You are getting the relative path of the image file. XMLHttpRequest cannot read the image like that. You should return the image URL like http://somedomain.com/storage/image.jpg from the laravel getImages() method.
i fixed it my own. had to change both backend and frontend.
fileSystem.php
'my_folder' => [
'driver' => 'local',
'root' => storage_path('app/public/uploads/my_folder')
],
controller method
public function getImages()
{
$filesToReturn = [];
$files = File::files(storage_path() . "/app/public/uploads/my_folder");
foreach ($files as $file) {
$fileName = basename($file);
$file = Storage::url('uploads/my_folder/' . $fileName);
array_push($filesToReturn, url($file));
}
return $this->apiResponse(['files' => $filesToReturn], $this->response_status_code, 200);
}
frontend method
async convertUploadedFilesToBase64(savedImages) {
let self = this;
for (let i = 0; i < savedImages.length; i++) {
fetch(savedImages[i])
.then(res => res.blob())
.then(blob => {
let reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function () {
let base64String = reader.result;
self.imageUrls.push({
file: base64String,
});
console.log('Base64 String - ', base64String);
console.log('Base64 String without Tags- ', base64String.substr(base64String.indexOf(', ') + 1));
}
});
}
},

Doing live search in codeigniter via ajax , mongodb

This is my ajax code which fetches all data from data and display in the table, but when I input an alphabet in search-box, it again fetches complete data inside the table
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "<?php echo base_url() ?>Appconfig/get_masteradmin_data?query="+query,true);
xhttp.onload= function()
{
if (xhttp.status >=200 && xhttp.status <400)
{
var data= JSON.parse(xhttp.responseText);
var html = '';
var i;
for(i=0; i<data.length; i++){
html +='<tr>'+
'<td>'+data[i].full_name+'</td>'+
'<td>'+data[i].username+'</td>'+
'<td>'+data[i].designation+'</td>'+
'<td>'+data[i].department+'</td>'+
'<td>'+data[i].official_mobile_no+'</td>'+
'<td>'+data[i].official_email_id+'</td>'+
'<td>'+data[i].select_user_type+'</td>'+
'<td>'+data[i].permission+'</td>'+
'</tr>';
}
showdata.insertAdjacentHTML('beforeend',html);
}
else
{
console.log("Try again after some time");
}
};
xhttp.send();
}
$('#search').keyup(function(){
var search = $(this).val();
//console.log(search);
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
This is my model for fetching data from my mongodb collection.
public function get_masteradmin_data($query)
{
$mongo = new \MongoDB\Driver\Manager('mongodb://localhost:27017');
$query= '';
//$filter = ['full_name' => 'www'];
$regex = new MongoDB\BSON\Regex ($query);
$filter = ['full_name'=>$regex,];
$options =[
'projection' => [
'_id' => 0,
'full_name' => 1,
'username' => 1,
'designation'=> 1,
'department'=> 1,
'official_mobile_no'=> 1,
'official_email_id'=> 1,
'select_user_type'=> 1,
'permission'=> 1,
],
'sort' => [
'_id' => -1
],
];
$query = new MongoDB\Driver\Query($filter, $options);
//$readPreference = new MongoDB\Driver\ReadPreference(MongoDB\Driver\ReadPreference::RP_PRIMARY);
$result = $mongo->executeQuery('justrack_db.master_admin', $query);
$res = array();
foreach($result as $r)
{
$res[] = $r;
}
return json_encode($res,true);
//return $res;
}
This is my controller for displaying data. I am not sure, but I think there is some issue in my controller, as I tried to echo $query but it shows nothing. I am not able to understand how to fix this.
public function get_masteradmin_data()
{
$query = '';
$this->load->model('AppconfigModel');
$this->master_admin();
if($this->input->post('query'))
{
$query = $this->input->post('query');
}
$result= $this->AppconfigModel->get_masteradmin_data($query);
echo ($result);
}

404 error occur while calling laravel API from ionic

i am trying to call API from ionic but it shows 404 error
here is my code for provider
remoteservice.ts
export class RemoteserviceProvider {
public headers = new Headers( { 'X-API-KEY' :
'xxxxxxxxx' });
public options = new RequestOptions({ headers: this.headers });
constructor(public http: Http) {
console.log('Hello RemoteserviceProvider Provider');
}
rec:any[]=[];
use:any[]=[];
login(credentials) {
return new Promise((resolve, reject) => {
this.http.post('http://localhost/my/v1/adminlogin', credentials,
{headers: this.headers})
.subscribe(res => {
resolve(res.json());
}, (err) => {
reject(err);
});
});
}
Login.ts
doLogin() {
this.showLoader();
this.remoteService.login(this.loginData).then((result) => {
this.loading.dismiss();
this.responseData = result;
console.log(this.responseData);
if(this.responseData.message=='Login Success'){
localStorage.setItem('loginData', JSON.stringify(this.responseData));
if(this.responseData.user_type==1){
if(this.responseData.project_type==null){
this.presentToast('You are not assigned to any project');
}
else{
if(this.responseData.project_type=='Concrete'){
console.log(this.responseData.p_id)
this.navCtrl.setRoot(ConcretePage,
{p_id:this.responseData.p_id, s_name:this.responseData.name,
project:this.responseData.project,
project_type:this.responseData.project_type,
location:this.responseData.location});
}
else if(this.responseData.project_type=='Bricks'){
this.navCtrl.setRoot(ProductionPage,
{p_id:this.responseData.p_id,s_name:this.responseData.name,
project:this.responseData.project,
project_type:this.responseData.project_type,
location:this.responseData.location});
}
else{
this.navCtrl.setRoot(DailyReportPage,
{p_id:this.responseData.p_id,s_name:this.responseData.name,
project:this.responseData.project,
project_type:this.responseData.project_type,
location:this.responseData.location});
}
}
My API code is laravel
index.php
<?php
//including the required files
require_once '../include/DbOperation.php';
require '.././libs/Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->hook('slim.before.dispatch', function () use ($app){
$headers = request_headers();
$response = array();
$app = \Slim\Slim::getInstance();
$api_key = $headers['X-API-KEY'];
// this could be a MYSQL query that parses an API Key table, for example
if($api_key == 'xxxxxxxxxxxxxxx') {
$authorized = true;
} else if ($api_key == NULL) {
$response["error"] = true;
$response["message"] = '{"error":{"text": "api key not sent"
}}';
$app->response->headers['X-Authenticated'] = 'False';
$authorized = false;
$app->halt(401, $response['message']);
} else {
$response["error"] = true;
$response["message"] = '{"error":{"text": "api key invalid" }}';
$app->response->headers['X-Authenticated'] = 'False';
$authorized = false;
}
if(!$authorized){ //key is false
// dont return 403 if you request the home page
$req = $_SERVER['REQUEST_URI'];
if ($req != "/") {
$app->halt('403', $response['message']); // or redirect, or
other something
}
}
});
$app->post('/adminlogin', function () use ($app) {
$json = $app->request->getBody();
$input = json_decode($json, true);
$mobile= (int)$input['mobile'];
$password = (string)$input['password'];
$db = new DbOperation();
$response = array();
$response['report'] = array();
if ($db->adminLogin($mobile,$password)) {
$admin = $db->getAdmin($mobile);
$admin1 = $db->getassignedproject($mobile);
$admin2 = $db->getprojecttype($admin1['p_id']);
$admin4 = $db->updateadminlogin($mobile,$password);
$response['error'] = false;
$response['p_id']=$admin1['p_id'];
$response['id'] = $admin['u_id'];
$response['name'] = $admin['username'];
$response['date'] = date('Y-m-d');
$response['user_type'] = $admin['user_type'];
$response['project'] = $admin1['p_name'];
$response['project_type'] = $admin2['p_type'];
$response['location'] = $admin2['location'];
$response['message'] = "Login Success";
} else {
$response['error'] = true;
$response['message'] = "Invalid username or password";
}
echoResponse(200, $response);
});
while am calling API using /adminlogin this shows 404 error
i don't know where i did wrong.
Anyone can please give me some idea to overcome this.
Thanks in Advance

Laravel 5 getClientOriginalExtension() returns empty string

I checked if file exists using Input::hasFile('File'), and it returns true and successfully got file's binary.
But Input::file('File')->getClientOriginalExtension() returns empty string.
Here's my controller
public function ConfirmWrite()
{
if (!Session::has('id')) {
return '0:Please log in.';
}
$Data = Request::all();
$Data['uid'] = Session::get('id');
$Data['mid'] = 0;
var_dump(Input::file('File')->getClientOriginalExtension());
return '1';
if (Input::hasFile('File')) {
$file = Input::file('File');
$rules = ['File' => 'mimes:jpeg,bmp,png,jpg|max:10000'];
$validator = Validator::make(['File' => $file], $rules);
if ($validator->fails()) {
return '0:Check your File.';
}
$Data['Thumbnail'] = $file->getClientOriginalExtension();
$destinationPath = 'images/post/thumbnail/';
$Content = Post::SaveContent($Data);
if($Data['Share'] == 'true'){
$fb = FacebookHelper::WithToken(Session::get('FbToken'));
$Link = URL::to('/post').'/'.$Content;
$fb->ShareLink($Link);
}
$upload_success = $file->move($destinationPath, $Content . '.' . $Data['Thumbnail']);
echo "asdfasdfasdf : ".$Data['Thumbnail'];
if ($upload_success) {
UsefulHelper::ImageResizing($destinationPath, $Content . '.' . $Data['Thumbnail'], 320, 'small');
UsefulHelper::ImageResizing($destinationPath, $Content . '.' . $Data['Thumbnail'], 700, 'medium');
UsefulHelper::ImageResizing($destinationPath, $Content . '.' . $Data['Thumbnail'], 1920, '');
foreach (explode(',', $Data['Tag']) as $tag) {
HashTag::SaveHashTag($tag, 'post', $Content);
}
return '1:' . $Content;
} else {
return '0:Somethings wrong';
}
} else {
$Content = Post::SaveContent($Data);
if($Data['Share'] == 'true'){
$fb = FacebookHelper::WithToken(Session::get('FbToken'));
$Link = URL::to('/post').'/'.$Content;
$fb->ShareLink($Link);
}
foreach (explode(',', $Data['Tag']) as $tag) {
HashTag::SaveHashTag($tag, 'post', $Content);
}
return '1:' . $Content;
}
}
And below code is Front-end Ajax code.
var fData = new FormData;
GlobalVar.Thumbnail == '' ? '' : fData.append('File', DataURLtoBlob(GlobalVar.Thumbnail));
fData.append('Title', $('.contents-details').find('h1').html());
fData.append('Subtitle', $('.contents-details').find('h2').html());
fData.append('Content', $('#post-editor').froalaEditor('html.get'));
fData.append('Align', EditorAlign);
fData.append('Tag', Tag);
fData.append('Share',GlobalVar.FBShare);
$.ajax({
url: '{{ URL::to('/post/write') }}',
type: 'post',
processData: false,
enctype: "multipart/form-data",
contentType: false,
cache: false,
data: fData,
headers: {
'X-CSRF-Token': '{{ csrf_token() }}',
},
success: function (result) {
var Check = $.trim(result).split(':');
$('.submit-loading').css('display', 'none');
if (Check[0] == '1') {
checkUnload = false;
location.href = '{{ URL::to('post') }}/' + Check[1];
} else {
console.log(result);
Warning(Check[1]);
}
},
});
I can't find where is bug code and mistake I made. Please help me. This make me mad.
The getClientOriginalExtension method returns the extension of the actual file uploaded some-image.pdf, this is not considered a safe value. Instead you could best use guessExtension.
The guessExtension method uses the actual mime type and returns the related file type.

Resources