How can I download using force_download php in ajax,
Is it possible ???
I have an ajax request like this :
function save(path, namaFile, namaExcel) {
$.ajax({
url: "<?php echo site_url('members/program_kecil/program_kecil/convert_csv_ke_excel'); ?>",
type: 'post',
data: {path: path,
nama: namaFile,
namaExcel: namaExcel
},
success: function (response) {
$('#modal_form').modal('hide'); // show bootstrap modal
}
});
}
This is the php :
class Program_kecil extends Members_Controller{
public function convert_csv_ke_excel() {
require_once APPPATH . "/libraries/CSVToExcelConverter.php";
$this->load->helper('file');
$this->load->helper('download');
CSVToExcelConverter::convert($this->input->post('path'), $this->input->post('namaExcel'));
$this->download_excel($this->input->post('namaExcel'));
echo json_encode($this->input->post('namaExcel'));
}
public function download_excel($file) {
header('Content-type: application/ms-excel');
header('Content-Disposition: attachment; filename=' . $file);
$filedownload = file_get_contents($file);
force_download($filedownload, null);
}
I just got my modal is closed;
P.S : in success ajax (callback) like this:
"D:\/xampp\/htdocs\/develop_tsurumaru\/assets\/uploads\/LJTD2508.xlsx"
Which is the path of excel will be downloaded.
Please advise.
Through AJAX you can't download file directly, You will need to open that path in new tab to download it.
Like this,
window.open('http://YOUR_HOST/develop_tsurumaru/assets/uploads/LJTD2508.xlsx', '_blank');
Update the URL to access the file from web instead of file system.
Related
I would like to download a pdf from my external URL, store it in my server and download it when the button was triggered by click by the user.
I have tried to store it to my server and its success, but then I don't know how to automatically download the pdf as the user wants after they click the button.
My view:
<button id=\"appPrintbutton\" name=\"appPrintbutton\" style=\"cursor:pointer;padding: 3px; margin: 2px;float:left;\" title=\"Cetak Dokumen\"><i class=\"fas fa-check fa-lg fa-fw\"></i>Cetak</button>
<script type="text/javascript">
$("#appPrintbutton").on('click', function() {
var selectedId=[];
selectedId.push(document.getElementById("txtNO_DOK").value);
$.ajax({
url: "<?php echo base_url().'index.php/finance/M_approve/DOWNLOAD_FILE_NILAI'?>",
type: 'POST',
data: {json: JSON.stringify(selectedId)},
dataType: 'json',
success: function (data) {
window.location.href = "<?php echo base_url().'index.php/finance/M_approve/';?>";
},
error: function (data) {
console.log('error');
}
});
return false;
});
</script>
And my Controller was:
public function DOWNLOAD_FILE_NILAI()
{
$msg="";
$status="";
$rptName="";
$pathdir="/wwwroot/php/download/";
$ieselon="ALL";
$data=$this->input->post('json');
$nodok=substr($data, 1, 9);
if($nodok!="" )
{
$randfname = Date("Y_m_d");
$fname = $nodok."_nilai".$randfname.".pdf";
$rptName="\wfinance\kas_cetak.rpt";
$strParamName= "&promptex-no_dok=".$nodok;
$strParamName.= "&promptex-terbilang=".$nodok;
$exportType="PDF";
$serverLink = "http://11.5.1.44:12000/ReCrystallizeServer/ViewReport.aspx?report=".$rptName;
$fullLink=$serverLink.$strParamName."&exportfmt=$exportType";
$fdata = file_get_contents($fullLink);
$fSaveAs=fopen($pathdir."$fname","w");
fwrite($fSaveAs, $fdata);
fclose($fSaveAs);
$status="OK";
}
$dataStatus[] = array(
'Status'=>$status,
'url'=>base_url(),
'fname'=>$fname,
'Msg'=>$msg
);
print_r(json_encode($dataStatus,JSON_PRETTY_PRINT));
}
My desired output:
Automatically download the pdf
Is it any way to do that?
You can use file_put_contents() function in PHP to read and write remote files to the server's directory.
$remote_file = 'http://example.com/path/to/pdffile.pdf';
$local_file = '/documents/new_file.pdf';
file_put_contents($local_file, file_get_contents($remote_file));
Update
If you are unable to write file directly, you can use two step way. First create blank file and after that write to it.
$local_file = fopen("/documents/new_file.pdf", "w")
This will create a file so other functions could write to it.
this way you can display files either from external/internal URL. And in case of downloading, you can provide local URL of /documents/new_file.pdf
So when the user clicks button you can hit ajax which triggers a server-side script which executes the code above.
Make sure your local directory /documents/ is writable by PHP process.
Read: https://www.php.net/manual/en/function.file-put-contents.php
Here i have one button, if i click the button means i want to download the one demo.xls file,using php i did, but now i want to do codeigniter, i tried but i am not able to do? please see my below code
<button class="btn btn-warning" id="download-btn">
<i class="fa fa-download" aria-hidden="true"></i> Download Demo File
</button>
<script type="text/javascript">
$(document).ready(function(){
$("#download-btn").click(function(e){
e.preventDefault();
$.ajax({
type:'POST',
url :"Staff/downloadDemoFile",
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
},
error:function(exception){
alert('Exeption:'+exception);
}
});
});
});
</script>
My controller
public function downloadDemoFile()
{
if($this->session->logged_in != TRUE){
$this->load->view('login');
}
else{
$download= $this->Add_staff_model->downloadFile();
}
}
My model
public function downloadFile()
{
$sFileName = 'demo.xls';
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$sFileName");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
// read the file from disk
readfile(UPLOAD_PATH_XLS.$sFileName);
}
Downloading a file from disk is pretty straightfoward using CodeIgniter Download Helper. Read the manual here.
public function downloadFile()
{
// load the helper somewhere, i.e in the constructor.
$this->load->helper('download');
// Use it when necessary
$sFileName = 'demo.xls'; // filename to be download. With path if necessary: /path/to/demo-xls
force_download($sFileName, NULL);
}
As a final consideration, in such a situation I wouldn't put the downloadFile() method in the model but in the controller itself.
I'm trying to download a file using force_download in codeigniter.
I create an AJAX call like this
$.ajax({
type: 'POST'
, url: '<?php echo base_url('downloadPayroll'); ?>'
, data: { filename: filename }
});
And here is my controller
public function downloadPayroll() {
$filename = $this->input->post('filename');
$fileContents = file_get_contents(base_url('assets/uploads/'. $filename));
force_download($filePath, $fileContents);
}
I know I have the correct path and filename but it doesn't download anything.
What am I doing wrong because the documentation for Download Helper is very limited.
Just a note to anyone else who may be having this problem: Make sure you have a file extension on the filename you supply for the first argument to force_download().
CodeIgniter uses this to set the MIME type, and it doesn't seem to work without.
for more CodeIgniter - force_download() problem.
$name = 'myfile.txt';//file extension is required
force_download($name, NULL);//if you dont want to send data set NULL
And Don't forget to load download helper first.
$this->load->helper('download');
Please try using below code. You are passing wrong variable name for force_download
$filename = $this->input->post('filename');
$fileContents = file_get_contents(base_url('assets/uploads/'. $filename));
$file='test.pdf';
force_download($file, $fileContents);
there is no way to download a file via an ajax request like that - try this instead
your JS File
$.ajax({
type: 'POST'
, url: '<?php echo base_url('downloadPayroll'); ?>'
, data: { filename: filename },
success: function(strUrl)
{
var link = document.createElement('a');
link.style = "display: none";
link.href = strUrl;
document.body.appendChild(link);
link.click();
setTimeout(function () {
document.body.removeChild(link);
}, 5000);
}
});
Your Controller:
public function downloadPayroll()
{
$filename = $this->input->post('filename');
echo base_url('assets/uploads/'. $filename);
}
you are missing the helper
public function downloadPayroll() {
$filename = $this->input->post('filename');
$fileContents = file_get_contents(base_url('assets/uploads/'. $filename));
$this->load->helper( 'download' );
force_download($filePath, $fileContents);
}
I've seen a lot of answers of this type of questions but none worked for me. I've a CSV object which has a createCSV function like this :
public function createCSV($url, $delimiter = ","){
$file = fopen($url, 'w');
foreach ($this->content as $line) {
fputcsv($file, $line, $delimiter);
}
fclose($file);
}
And I want to download it directly from the browser so here is what I do :
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="'.$filename.'"');
$csv_file->createCSV('php://output');
This part of code is execute with an AJAX call and even if the header is set to text/csv the download doesn't work but in the response tab I can see the content of my csv. I've tried with different header but none of them worked. How can I do to download the CSV ?
EDIT
The thing is that I don't have a URL for my CSV and I don't want to store the file somewhere, I just want to build the file and download directly with the browser
Try this code:
$('#exportcsv').click(function(){
var self = this;
$.ajax({
url : '/exportcsv',
method : 'get',
success : function(response)
{
console.log(response);
var csvData = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(response);
$(self).attr({
'download': 'publisher.csv',
'href': csvData,
'target': '_blank'
});
// window.open(uri, 'test.csv');
}
})
})
I'm trying to write a method in a php class that will use ajax to execute a php function that will push a file back to the browser.
It seems like its trying to write the file to the modx log, getting a lot of binary garbage in there.
Here is the method:
public function pushDocuments($formdata){
$data = $formdata['formdata'];
$file = MODX_PROTECTED_STORAGE . $data['target'];
$file_name = basename($file);
if (file_exists($file)) {
header("Content-Disposition: attachment; filename=\"$file_name\"");
header("Content-Length: " . filesize($file));
header("Content-Type: application/octet-stream;");
readfile($file);
};
$output = array(
'status' => 'success',
'error_messages' => array(),
'success_messages' => array(),
);
$output = $this->modx->toJSON($output);
return $output;
}
and here is the jquery:
$('.btn-get-document').click(function(){
var target = $(this).attr('data-target');
var postdata = {"snippet":"DataSync", "function":"pushDocuments", "target": target}; // data object ~ not json!!
console.log('target = ' + target + postdata );
$.ajax({
type: "POST",
url: "processors/processor.ajax.generic/",
dataType : "json",
cache : false,
data: postdata, // posting object, not json
success: function(data){
if(data.status == 'success'){
console.log("SUCCESS status posting data");
}else if(data.status == 'error'){
console.log("error status posting data");
}
},
error: function(data){
console.log("FATAL: error posting data");
}
});
});
it's running through the scripts and giving a success in the console [because I am forcing success] but no file is prompted for download and the binary garbage shows up in the modx log
What am I doing wrong?
In order to download a file, you'd have to use JS to redirect to the file's location. You can't pull the file contents through AJAX and direct the browser to save those contents as a file.
You would need to structurally change your setup. For instance, your PHP script can verify the existence of the file to be downloaded, then send a link to JS in order to download the file. Something like this:
if ( file_exists( $file )) {
$success_message = array(
'file_url' => 'http://example.com/file/to/download.zip'
);
}
$output = array(
'status' => 'success',
'error_messages' => array(),
'success_messages' => $success_message
);
Then modify the "success" portion of your AJAX return like this:
success: function( data ) {
if ( data.status == 'success' ) {
location.href = data.success_messages.file_url;
} else if ( data.status == 'error' ) {
console.log( 'error status posting data' );
}
},
Since you're directing to a file, the browser window won't actually go anywhere, so long as the file's content-disposition is set to attachment. Typically this would happen if you directed to any file the browser didn't internally handle (like a ZIP file). If you want control over this so that it downloads all files (including things the browser may handle with plugins), you can direct to another PHP script that would send the appropriate headers and then send the file (similar to the way you're sending the headers and using readfile() in your example).
#sean-kimball,
You might want to extend MODX's class based processor instead:
https://github.com/modxcms/revolution/blob/master/core/model/modx/processors/browser/file/download.class.php
It does the download from any media source and also access checking if you want.
Its implementation on manager side is:
https://github.com/modxcms/revolution/blob/master/manager/assets/modext/widgets/system/modx.tree.directory.js#L553
Back to your case, these examples might bring you some ideas.
JS Example:
$.ajax({
type: "POST",
// read my note down below about connector file
url: "assets/components/mypackage/connectors/web.php",
dataType : "json",
cache : false,
data: {
action: 'mypath/to/processor/classfile'
}
success: function(data){
},
error: function(data){
console.log("FATAL: error posting data");
}
});
Processor example:
<?php
require_once MODX_CORE_PATH . 'model/modx/processors/browser/file/download.class.php';
class myDownloadProcessor extends modBrowserFileDownloadProcessor {
// override things in here
}
return 'myDownloadProcessor';
For this, I also suggest you to use MODX's index.php main file as the AJAX's connector so the $modx object in processor inherits the access permission as well.
http://www.virtudraft.com/blog/ajaxs-connector-file-using-modxs-main-index.php.html