Laravel, ajax base64 image not uploading correctly - javascript

I'm using DropzoneJS to upload my images. So what I do is to take the base64URL generated by dropzoneJS, and then try to upload as follows:
$( document ).ready(function() {
var endpoint= $("#endpoint").val();
var unit = {
name: '',
description: '',
image: '',
base64Image: '',
themes: []
}
$("#create-unit-btn").on("click", function() {
unit.name = $("#create-name").val();
unit.description = $("#create-description").val();
unit.base64Image = $('#imageDropzone')[0].dropzone.files[0].dataURL;
var data = {
'_token': $('meta[name=csrf-token]').attr('content'),
'unit': unit
}
console.log(data);
$.ajax({
type: "POST",
url: endpoint,
data: data,
success: function(result){
console.log(result);
}
});
});
function validate() {
}
});
Then to upload the Image I use the following code:
public function create( Request $request ) {
$data = [];
$code = 200;
try {
$unit = new Unit();
$unit->name = request()->input('unit.name');
$unit->description = request()->input('unit.description');
$url = ImageHandler::StoreBase64ToFile($request->input('unit.base64Image'));
$unit->image = $url;
$unit->save();
$data['unit'] = $unit;
} catch ( \Illuminate\Database\QueryException $e ) {
// There was an error
$code = Response::HTTP_UNPROCESSABLE_ENTITY;
$data = [];
$data['error'] = ErrorResponse::create($code, $e->getMessage());
} catch( ModelNotFoundException $e ) {
return response()->json(['error' => 'invalid operation'], 406);
}
return response()->json($data, $code);
}
The ImageHandler class does the following:
<?php
namespace App\Libraries;
use Storage;
class ImageHandler {
/**
* Store a base64 image into the file system this data has to be
* sended without any header info like:
* data:image/png;base64
* So the info will look something like iVBORw0....hEUgAAAcQ==
* #param string $base64Data information
* #param string $filename the filename if not defined then it generates
* a random name
* #param string $disk disk location, check Storage documentation of
* laravel, by default is stored on the public folder
* so you'll have to run
* php artisan storage:link
* to make the symbolink links
* #return string url location of the file
*/
public static function StoreBase64ToFile($base64Data,
$filename = null,
$disk = 'public')
{
if (strlen($base64Data) < 10) {
return null;
}
$image = base64_decode($base64Data);
if ($filename == null) {
$filename = str_random(16);
$filename .= '_'.time();
$filename .= '.png';
}
$path = 'images/'.$filename;
$result = Storage::disk($disk)->put($path, $image, 'public');
if ($result) {
$url = Storage::disk($disk)->url($path);
return $url;
}
return null;
}
}
But when I upload the image, even that the process ends correctly, when I try to open the file from my file browser (finder on MacOs), I can't see the uploaded image. I mean the file it’s there but I cant see the content of the image
I don't know why is not been uploaded correctly.

It was an error of format when I stored the Image. In order to upload the file without any problem I had to do the following before send the request: unit.base64Image = unit.base64Image.replace("data:image/png;base64,", "");

Related

server to server partial download

So I am trying to transfer/copy a large file from a remote server to my server in separate parts or chunks. I tried the script provided here:
https://stackoverflow.com/a/4000569/7559794
I made some changes and gave a form to the script and used AJAX to communicate with PHP script as follows:
The index.html contains a form with POST method and a submit button that calls the following function OnClick:
<script>
function stratdown() {
var partsizevalue = $('#psize').val();
var dfilename = $('#dfile').val();
var sfilename = $('#sfile').val();
$.ajax({
type: "POST",
url: 'trigger.php',
data:{dfile: dfilename, sfile: sfilename, psize: partsizevalue}, //{value: a, cID: cID}
success:function(result) {
alert(result);
}
});
}</script>
the file trigger.php contains the following script:
<?php
require 'partdown.php';
$infile = $_POST["dfile"];
$outfile = $_POST["sfile"];
$partsize = $_POST["psize"];
echo $mesg = DownInParts::copyfile_chunked($infile, $outfile, $partsize);
?>
and the required partdown.php contains:
<?php
/**
* Copy remote file over HTTP one small chunk at a time.
*
* #param $infile The full URL to the remote file
* #param $outfile The path where to save the file
*/
class DownInParts
{
public function copyfile_chunked($infile, $outfile, $partsize)
{
$chunksize = $partsize * 1024; // 10 Megs
/**
* parse_url breaks a part a URL into it's parts, i.e. host, path,
* query string, etc.
*/
$parts = parse_url($infile);
$i_handle = fsockopen($parts['host'], 80, $errstr, $errcode, 5);
$o_handle = fopen($outfile, 'wb');
if ($i_handle == false || $o_handle == false) {
return false;
}
if (!empty($parts['query'])) {
$parts['path'] .= '?' . $parts['query'];
}
/**
* Send the request to the server for the file
*/
$request = "GET {$parts['path']} HTTP/1.1\r\n";
$request .= "Host: {$parts['host']}\r\n";
$request .= "User-Agent: Mozilla/5.0\r\n";
$request .= "Keep-Alive: 115\r\n";
$request .= "Connection: keep-alive\r\n\r\n";
fwrite($i_handle, $request);
/**
* Now read the headers from the remote server. We'll need
* to get the content length.
*/
$headers = array();
while(!feof($i_handle)) {
$line = fgets($i_handle);
if ($line == "\r\n") break;
$headers[] = $line;
}
/**
* Look for the Content-Length header, and get the size
* of the remote file.
*/
$length = 0;
foreach($headers as $header) {
if (stripos($header, 'Content-Length:') === 0) {
$length = (int)str_replace('Content-Length: ', '', $header);
break;
}
}
/**
* Start reading in the remote file, and writing it to the
* local file one chunk at a time.
*/
$cnt = 0;
while(!feof($i_handle)) {
$buf = '';
$buf = fread($i_handle, $chunksize);
$bytes = fwrite($o_handle, $buf);
if ($bytes == false) {
return false;
}
$cnt += $bytes;
/**
* We're done reading when we've reached the content length
*/
if ($cnt >= $length) break;
}
fclose($i_handle);
fclose($o_handle);
return $cnt;
}
}
?>
I didn't manage to make it function. I have however tried to add the action "trigger.php" to the form in order to call PHP directly yet The file I downloaded was (0 Kb) in size. Any ideas.
I think I have just missed adding this two line in the < head > section due to stress.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This did the trick for me. Now I need a progress bar and a success alert.

How to use the extra params in ExtJS Upload Widget by Ivan Novakov

I am using this upload widget in my web application.
I am using the FormDataUploader and I am able to upload files to a server directory quite well. However, I wanted to send extra parameters as well to the php file handling the upload. This is what I attempted:
var uploadPanel = Ext.create('Ext.ux.upload.Panel', {
uploader : 'Ext.ux.upload.uploader.FormDataUploader',
uploaderOptions : {
url : 'uploadGallery.php'
},
synchronous : true,
uploadParams : {
ID_Person : ID_Person,
ID_CI : ID_CI
}
});
As you can see, I used the uploadParams, however, my PHP couldn't seem to receive it. In my php file, I have:
$ID_Person = $_GET['ID_Person'];
$ID_CI = $_GET['ID_CI'];
However, my PHP seems to be unable to get these params.
What I did next was to use the default ExtJS Uploader as such:
var uploadPanel = Ext.create('Ext.ux.upload.Panel', {
uploaderOptions : {
url : 'uploadExtJS.php'
},
synchronous : true,
uploadParams : {
ID_Person : ID_Person,
ID_CI : ID_CI
}
});
At first, I used the old PHP file which was able to get the extra params I sent. However, it seems that I needed to use a different PHP file for the ExtJS uploader.
This is what my PHP file looks like:
<?php
/**
* Example processing of raw PUT/POST uploaded files.
* File metadata may be sent through appropriate HTTP headers:
* - file name - the 'X-File-Name' proprietary header
* - file size - the standard 'Content-Length' header or the 'X-File-Size' proprietary header
* - file type - the standard 'Content-Type' header or the 'X-File-Type' proprietary header
*
* Raw data are read from the standard input.
* The response should be a JSON encoded string with these items:
* - success (boolean) - if the upload has been successful
* - message (string) - optional message, useful in case of error
*/
require __DIR__ . '_common.php';
$config = require __DIR__ . '_config.php';
error_reporting(-1);
ini_set('display_errors', 'On');
/*
* You should check these values for XSS or SQL injection.
*/
if (!isset($_SERVER['HTTP_X_FILE_NAME'])) {
_error('Unknown file name');
}
$fileName = $_SERVER['HTTP_X_FILE_NAME'];
if (isset($_SERVER['HTTP_X_FILENAME_ENCODER']) && 'base64' == $_SERVER['HTTP_X_FILENAME_ENCODER']) {
$fileName = base64_decode($fileName);
}
$fileName = htmlspecialchars($fileName);
$mimeType = htmlspecialchars($_SERVER['HTTP_X_FILE_TYPE']);
$size = intval($_SERVER['HTTP_X_FILE_SIZE']);
$inputStream = fopen('php://input', 'r');
// $outputFilename = $config['upload_dir'] . '/' . $fileName;
$outputFilename = 'gallery' . '/' . $fileName;
$realSize = 0;
$data = '';
if ($inputStream) {
if (! $config['fake']) {
$outputStream = fopen($outputFilename, 'w');
if (! $outputStream) {
_error('Error creating local file');
}
}
while (! feof($inputStream)) {
$bytesWritten = 0;
$data = fread($inputStream, 1024);
if (! $config['fake']) {
$bytesWritten = fwrite($outputStream, $data);
} else {
$bytesWritten = strlen($data);
}
if (false === $bytesWritten) {
_error('Error writing data to file');
}
$realSize += $bytesWritten;
}
if (! $config['fake']) {
fclose($outputStream);
}
} else {
_error('Error reading input');
}
if ($realSize != $size) {
_error('The actual size differs from the declared size in the headers');
}
_log(sprintf("[raw] Uploaded %s, %s, %d byte(s)", $fileName, $mimeType, $realSize));
_response();
However, I am getting an Internal Server 500 Error - Meaning that there was something probably wrong with my php file.
I mainly have two questions:
How do I make the uploadParams work with the FormDataUploader?
How do I write a PHP uploader for an ExtJS Data Uploader?
Got it to work.
The uploadExtJS.php file should look like:
<?php
/**
* Example processing of raw PUT/POST uploaded files.
* File metadata may be sent through appropriate HTTP headers:
* - file name - the 'X-File-Name' proprietary header
* - file size - the standard 'Content-Length' header or the 'X-File-Size' proprietary header
* - file type - the standard 'Content-Type' header or the 'X-File-Type' proprietary header
*
* Raw data are read from the standard input.
* The response should be a JSON encoded string with these items:
* - success (boolean) - if the upload has been successful
* - message (string) - optional message, useful in case of error
*/
// require __DIR__ . '_common.php';
// $config = require __DIR__ . '_config.php';
require_once '_common.php';
$config = require_once '_config.php';
error_reporting(-1);
ini_set('display_errors', 'On');
/*
* You should check these values for XSS or SQL injection.
*/
if (!isset($_SERVER['HTTP_X_FILE_NAME'])) {
_error('Unknown file name');
}
$fileName = $_SERVER['HTTP_X_FILE_NAME'];
if (isset($_SERVER['HTTP_X_FILENAME_ENCODER']) && 'base64' == $_SERVER['HTTP_X_FILENAME_ENCODER']) {
$fileName = base64_decode($fileName);
}
$fileName = htmlspecialchars($fileName);
$mimeType = htmlspecialchars($_SERVER['HTTP_X_FILE_TYPE']);
$size = intval($_SERVER['HTTP_X_FILE_SIZE']);
$inputStream = fopen('php://input', 'r');
$outputFilename = $config['upload_dir'] . '/' . $fileName;
// $outputFilename = 'gallery' . '/' . $fileName;
$realSize = 0;
$data = '';
if ($inputStream) {
if (! $config['fake']) {
$outputStream = fopen($outputFilename, 'w');
if (! $outputStream) {
_error('Error creating local file');
}
}
while (! feof($inputStream)) {
$bytesWritten = 0;
$data = fread($inputStream, 1024);
if (! $config['fake']) {
$bytesWritten = fwrite($outputStream, $data);
} else {
$bytesWritten = strlen($data);
}
if (false === $bytesWritten) {
_error('Error writing data to file');
}
$realSize += $bytesWritten;
}
if (! $config['fake']) {
fclose($outputStream);
}
} else {
_error('Error reading input');
}
if ($realSize != $size) {
_error('The actual size differs from the declared size in the headers');
}
_log(sprintf("[raw] Uploaded %s, %s, %d byte(s)", $fileName, $mimeType, $realSize));
_response(true, "okay");
_common.php looks like:
<?php
function _log($value){
error_log(print_r($value, true));
}
function _response($success = true, $message = 'OK'){
$response = array(
'success' => $success,
'message' => $message
);
echo json_encode($response);
exit();
}
function _error($message){
return _response(false, $message);
}
_config.php should look like:
<?php
return array(
'upload_dir' => 'gallery',
'fake' => false
);
?>
and now I'm working on using a unique name using uniqid() and microtime(), as well as saving the images to a subdirectory (or any folder under your main upload/gallery folder) using the uploadParams() property.
EDIT 1: RENAMING THE UPLOADED FILE
just change this line:
$fileName = htmlspecialchars($fileName);
to:
$fileName = uniqid() . '_' . microtime();
EDIT 3: TO GET THE CUSTOM SUB DIRECTORY FROM YOUR ADDITIONAL PARAMS
First, make sure than when you create your Upload Dialog from your ExtJS web app, you do this:
var uploadPanel = Ext.create('Ext.ux.upload.Panel', {
uploaderOptions : {
url : 'uploadExtJS.php'
},
synchronous : true,
uploadParams : {
ID_1 : ID_1,
ID_2 : ID_2 // you can put waaay more if you want
}
});
and in your uploadExtJS.php, do this (between the part where you define your new file name and the part where you check for input stream)
$fileName = uniqid() . '_' . microtime();
$mimeType = htmlspecialchars($_SERVER['HTTP_X_FILE_TYPE']);
$size = intval($_SERVER['HTTP_X_FILE_SIZE']);
$ID_1 = $_GET['ID_1'];
$ID_2 = $_GET['ID_2'];
$newFilePath = $config['upload_dir'] . '/' . $ID_1 . '/' . $ID_2;
if (!file_exists($newFilePath)) {
mkdir($newFilePath, 0777, true);
}
$inputStream = fopen('php://input', 'r');
$outputFilename = $newFilePath . '/' . $fileName;
$realSize = 0;
$data = '';
As you can see, I defined a $newFilePath variable, checked if it was existing before making it, then uploaded to that directory.
Hope this helps anyone who encounters the issue in the future.

codeigniter file upload with verot_upload class and dropzone.js

I'm trying to get working my upload script.
I'm using CodeIgniter, dropzone.js and Verot_upload class
form:
<form action="/admin/images/upload"
enctype="multipart/form-data" method="post"
class="dropzone"
id="my-awesome-dropzone"></form>
<script src="/skin/js/dropzone.js"></script>
and /admin/images/upload method
public function upload()
{
$data = array();
$this->load->library('verot_upload');
if ($this->authentication->is_loggedin())
{
if (!empty($_FILES))
{
// $tempFile = $_FILES['file']['tmp_name'];
$foo = new Verot_upload($_FILES['file']);
if ($foo->uploaded)
{
// save uploaded image with no changes
$foo->Process('./media/test/');
}
}
} else
{
redirect('/admin/login/', 'refresh');
}
}
it works with regular style:
function upload()
{
if (!empty($_FILES))
{
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . '/uploads/';
$targetFile = $targetPath . $_FILES['file']['name'];
move_uploaded_file($tempFile, $targetFile);
// save data in database (if you like!)
}
}
But not with verot_upload.
So the issue was that, I was trying to upload image as in example at the class initialization.
if I initialize empty class and then use upload method everything works.
/**
* Method for uploading Images from dropdown form.
*
* #param $size
* #param $path
* #param $file
*/
public function upload_image($size, $path, $file)
{
$this->load->library('verot_upload');
$foo = new Verot_upload();
$foo->upload($file);
if ($foo->uploaded)
{
$foo->image_resize = true;
$foo->image_x = $size;
$foo->image_ratio_y = true;
$foo->Process($path);
if ($foo->processed)
{
$new_path = substr($foo->file_dst_pathname,1);
$this
->db
->set('date_created', 'NOW()', false)
->set('path', $new_path, true)
->insert('wysiwyg_img_uploads');
$foo->Clean();
}
}
}

Could someone clarify this code snippet for me?

This piece should create a csv file. The method that is calling to the nonAjaxPost is:
function exportCSV()
{
nonAjaxPost('getExport', 'post', {action: '/getView', 'view': current_pi, 'parameters': encodeURIComponent(JSON.stringify(current_parameters))});
}
function nonAjaxPost(action, method, input) {
"use strict";
var form;
form = $('<form />', {
action: action,
method: method,
style: 'display: none;'
});
if (typeof input !== 'undefined') {
$.each(input, function (name, value) {
$('<input />', {
type: 'hidden',
name: name,
value: value
}).appendTo(form);
});
}
form.appendTo('body').submit();
}
My problem is that i just can't seem to understand how this is going to create a csv file for me. I'm probaly missing out on something that i just can't see.
I really hope someone could help me out.
Update:
This is the getExport function:
$databundle = $this->_getData();
$data = $databundle['rows'];
$columns_all = $databundle['columns'];
$columns = array("Id");
foreach($data[0] as $key => $column) {
$column = "";
$found = false;
foreach($columns_all as $col_search) {
if($col_search['key'] == #$key) {
$found = true;
$column = $col_search['title'];
break;
}
}
if($found) {
//echo $key . ",";
$columns[] = $column;
}
}
$contents = putcsv($columns, ';', '"');
foreach($data as $key => $vals) {
if(isset($vals['expand'])) {
unset($vals['expand']);
}
array_walk($vals, '__decode');
$contents .= putcsv($vals,';', '"');
}
$response = Response::make($contents, 200);
$response->header("Last-Modified",gmdate("D, d M Y H:i:s") . " GMT");
$response->header("Content-type","text/x-csv");
$response->header("Content-Disposition","attachment; filename=".str_replace(" ","_",$databundle['title'])."_".date("Y-m-d_H:i").".csv");
return $response;
It also calls the getData function which is this:
$viewClass = str_replace('/', '', (isset($_POST['view']) ? $_POST['view'] : $_GET['view']));
$fileView = '../app/classes/view.'.$viewClass.'.php';
if(file_exists($fileView))
{
require_once($fileView);
$className = 'view_'.$viewClass;
if(class_exists($className))
{
$view = new $className();
//Seek for parameters
if(isset($_REQUEST['parameters']))
{
//Decode parameters into array
$parameters = json_decode(urldecode((isset($_POST['parameters']) ? $_POST['parameters'] : $_GET['parameters'])),true);
//Get supported parameters
$parameterTypes = $view->getVars();
$vars = array();
foreach($parameterTypes as $key => $type)
{
//If a value is found for a supported parameter in $_GET
if(isset($parameters[$key]))
{
switch($type)
{
case 'int':
$vars[$key] = intval($parameters[$key]);
break;
case 'float':
$vars[$key] = floatval($parameters[$key]);
break;
case 'filterdata':
// todo: date validation
$vars[$key] = $parameters[$key];
break;
}
}
}
$view->setVars($vars);
}
return $view->getData();
}
else {
/*
header('HTTP/1.1 500 Internal Server Error');
echo 'Class ' . $className . ' does not exist.';
*/
return false;
}
}
else {
/*
header('HTTP/1.0 404 Not Found');
die('Cannot locate view (' . $fileView . ').');
*/
return false;
I hope this is sufficient.
In short what i am trying to find out is that the csv that it produces has more columns than columns headers and where the difference comes from
My guess would be that the page you are calling (on the server) is generating the CSV file.
You would need to write code on the server to do the conversion.
This method is making a post request to getView page. Your csv create code would be present on getView page.
This is the front end code that creates an invisible form with your data: current_parameters.
See the content of current_parameters in the the current file.
Review back-end code and look for the "getExport" function (it should be the current php file loaded)
If you just copied this function from some example... you have to add also the back-end code on your own.
Update:
look at the getExport code:
$contents = putcsv($columns, ';', '"');
$contents .= putcsv($vals,';', '"');;
First row insert the titles , and the second loops the data and insert the other rows.
Print the content of $columns and $vals and see what is happening.
There are some strange conditions for filtering the columns... but can help you if you don't show the data you try to parse.

How to generate an excel file using js

I have a UI that shows a CRUD(create, read, update and delete) account of an employee. Now, I want to add a generate button that when its click, a window will pop-up that will show and ask if the following data in the grid lines under the UI are to be open or saved using the excel report.Also, I have already EXcelPhp library.
Here's my code for my 'actions.class.php':
public function executeLoadEmployeeList(sfWebRequest $request)
{
// $start = $request->getParameter('start') ? $request->getParameter('start'): 2;
// $limit = $request->getParameter('limit') ? $request->getParameter('limit'): 2;
$query = pg_escape_string($request->getParameter('query'));
$start = $request->getParameter('start');
$limit = $request->getParameter('limit');
if(isset($limit))
{
$page = $start / $limit;
$page ++;
}
else
$page = 1;
$criteria = Doctrine_Query::create();//what is the query?? is it select,inset,update,delete?
$criteria->select("(fname || ' ' || lname) AS fullname, department");
$criteria->from('Employees'); // Select * from profile
$criteria->orderBy('id'); // order by id
//print $criteria->getSqlQuery();
//die();
if($query!=null)
{
$criteria->where("(fname ilike '%$query%' or lname ilike '%$query%' or department ilike '%$query%')"); //where (uname ilike '%$query%' or status ilike '%$query%')
}
$allData = $criteria->fetchArray();
// print "<pre>";
// print_r($allData);
// die();
$this->pager = new sfDoctrinePager('Employees', 20); //what is sfdoctrine about? dont mind this.. this is a symphony built in class for pager
$this->pager->setQuery($criteria);
$this->pager->setPage($page);
$this->pager->init();//What is the purpose of this line? //initialize sfDoctrinePager
$result['data'] = $this->pager->getResults();
$result['totalCount'] = count($allData);
$result['limit'] = $limit;
$result['page'] = $page;
$result['query'] = $query;
die(json_encode($result));
}
public function executeAddEmployee(sfWebRequest $request)
{
try{
$fname = $request->getParameter('fname');
$lname = $request->getParameter('lname');
$department = $request->getParameter('department');
$Employee = new Employees();
$Employee->fname = $fname;
$Employee->lname = $lname;
$Employee->department = $department;
//save the data to the database
$Employee->save();
$data = array("success"=> true, "data"=>"Employee Added.");
}
catch(Exception $e)
{
$data = array("success"=> false, "data"=>$e->getMessage());
}
//$data is a return value of trycatch
die(json_encode($data));
}
public function executeDeleteEmployee(sfWebRequest $request)
{
try{
//what is Doctrine::getTable's purpose // to get the table profile
$this->forward404Unless($Employee = Doctrine::getTable('Employees')->find(array($request->getParameter('id'))), sprintf('Employee ID in Form does not exist (%s).', $request->getParameter('id')));
$Employee->delete();
$data = array("success"=> true, "data"=>"Employee record is Deleted.");
} catch(Exception $e) {
$data = array("success"=> false, "data"=>$e->getMessage());
}
//$data is a return value of trycatch
die(json_encode($data));
}
public function executeEditEmployee(sfWebRequest $request)
{
try{
$this->forward404Unless($Employee = Doctrine::getTable('Employees')->find(array($request->getParameter('id'))), sprintf('Employee ID in Form does not exist (%s).', array($request->getParameter('id'))));
$criteria = Doctrine_Query::create();
$criteria->select('fname,lname,department');
$criteria->from('Employees');
$criteria->where('id = ?', $request->getParameter('id'));//('id = ?', $request->getParameter('id') means... id = $request->getParameter('id')
$result = $criteria->fetchArray();
$record['fname'] = $Employee['fname'];
$record['lname'] = $Employee['lname'];
$record['department'] = $Employee['department'];
$data = array("success"=> true, "data"=>$record);
} catch(Exception $e) {
$data = array("success"=> false, "data"=>$e->getMessage());
}
//$data is a return value of trycatch
die(json_encode($data));
}
public function executeUpdateEmployee(sfWebRequest $request)
{
try{
$Employee = Doctrine::getTable('Employees')->find(array($request->getParameter('id')));
$Employee->fname = $request->getParameter('fname');
$Employee->lname = $request->getParameter('lname');
$Employee->department = $request->getParameter('department');
//save the update to the database
$Employee->save();
$data = array("success"=> true, "data"=>"Employee Successfully Updated.");
}
catch(Exception $e)
{
$data = array("success"=> false, "data"=>$e->getMessage());
}
//$data is a return value of trycatch
die(json_encode($data));
}
public function executeGenerateEmployee(sfWebRequest $request)
{
// ...
}**
What I've tried so far is setting only the generate button and there's no action yet. This is under my try.js:
var generateItem = new Ext.Action ({
text: 'Generate Excel Report',
width: 60,
enabled: true,
});
Could someone help me regarding this issue?
You can not generate an excel file without using a server side language / script. You can just prepare how it Will look and add some functions to make it functional like write, delete etc.
You can generate an Excel spreadsheet without any server side processing however you'll have a hellish time with browser support.
In theory you could generate an excel formatted file in js then simply do a window.open with the data URI.
for example here's a javascript generated image:
window.open('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD///+l2Z/dAAAAM0lEQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4Ug9C9zwz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC');
however.. it'll probably not be supported in most of the browsers for Excel data URIs:
here's another similar question:
Data URI used to export to CSV/Excel (no server-side request) : browser support/limitations?

Categories