Force Download in Codeigniter doesn't work - php

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);
}

Related

$request->file keeps returning tmp path

I'm trying to upload a file using laravel and vue. When i console.log() the file, I get the picture below but in the controller, I'm receiving a tmp path only.
Vue
onFileChange(e) {
ths.file = e.target.files[0];
console.log(this.file)
},
submit(){
let form= new FormData()
form.append('file', this.file)
axios.post('/api/archieve',form).then(res=>{
//
})
},
Controller
return $request->file //returns "C:\xampp\tmp\php5E67.tmp"
UPDATE
I've checked using dd($request->file('file')); and it returns the below image but the realPath is wrong. The image is stored in a different folder on my pc.
Please try add header.
onFileChange(e) {
this.file = e.target.files[0];
console.log(this.file)
},
submit() {
let form= new FormData()
form.append('file', this.file)
axios.post('/api/archieve', form, {
headers: { 'Content-Type': 'multipart/form-data' }
}).then(res=>{
//
})
},
and in you controller, check
$request->file('file');
To store file
use Illuminate\Support\Facades\Storage;
....
$file = $request->file('file');
$path = 'my-uploads'; // path or folder where to save it
$storePath = Storage::put($path, $file);
$fileName = basename($storePath); // generated file name
$filePath = $path . '/' . $fileName; // path of file in your storage

force_download in ajax and php

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.

php script to save image with proper extension

I made some javascrit code base on image uploader to save an image to the server using php. This is my code :
var reader = new FileReader();
reader.readAsDataURL(files[0]);
reader.onload = function(event) {
var base64 = reader.result;
//console.log(base64);
$.ajax({
url: 'imageapi.php',
method: 'post',
data: {src :base64 },
type:"POST",
contentType:"application/x-www-form-urlencoded",
success: function(response) {
alert('Files uploaded successfully.');
}
});
}
The uploaded file should be : text, png or svg
I want to save the file with proper extension on server. Could anyone help to solve my problem ?
I've tried using this code to get extension but it didn't work
echo $mime_type = finfo_buffer($f, $_POST['src'], FILEINFO_MIME_TYPE);
Please help me, How to save image on server with proper extension
Following code gets filename at first and then extracts it's extension.
$path = $_FILES['src']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);

Using AJAX to send data to Coder Igniter controller function results in a 500 Internal Server Error

I am trying to use AJAX to send data from a Code Igniter view to a controller that will handle the data as needed. I'm gathering the data using a JQuery plugin (Handsontable) and when the user hits the "save" button it extracts the required data from the table and executes the ajax function.
$.ajax({
url: "/survey/save",
data: {"data": data},
type: "POST",
});
I am able to send it to a regular .php file which collects the data with $_POST but not my controller.
public function save() {
$data = $this->input->post('data');
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
for ($i = 0, $size = count($data); $i < $size; ++$i) {
fwrite($fh, $data[$i][0]."\t".$data[$i][1]."\t".$data[$i][2]."\n");
}
fclose($fh);
}
The above code is not what I really want the controller to do but if can successfully execute this code, I will be able to do what I wish.
I have a feeling it has something to do with the URL of the ajax function but I am extremely new to all of these languages and am probably overlooking something simple. Please let me know if I should include any other code!
Hey you have to change in ajax url The format of url must be absolute path for e.g.
In your view the ajax should be like this
$.ajax({
url:'<?php echo site_url('survey/save'); ?>',
type: 'post',
data: "data="+data,
beforeSend:function(){
//before send code for e.g. put a loader
},
success:function(result){
// success result code goes here
},
error:function(jqXHR, status, error){
if(status!='error')
alert(error);
}
});
Now in your controller you can get the data
$data=$this->input->post('data');
and one more thing you have to use relative path when your using fopen for e.g.
//you have used
$myFile = "testFile.txt";
//instead of that you have to use
$myFile="./YOUR_FOLDER_NAME/YOUR_FILE_NAME";
and you can set in your config.php
$config['base_url'] = '';
Answering my own question in case it helps others. The problem was my csrf settings. I realized turning off csrf protection fixed the problem but I didn't want to keep csrf protection off. I think CI may have came out with a whitelist to fix this but I just edited my config file as follows:
if(stripos($_SERVER["REQUEST_URI"],'/survey') === FALSE)
{
$config['csrf_protection'] = TRUE;
}
else
{
$config['csrf_protection'] = FALSE;
}
If you have done your config file in the CI Application/Config folder
$config['base_url'] = 'http://yourwebsite.com/';
then for your url it is
"<?php echo base_url();?>survey/save",
The very simple and easy way try this code:
first you must have set your base_url in application/confiq.php
or with .htaccess
your script:
<script type='text/javascript'>
var base_url = '<?=base_url()?>';
function m_ajax()
{
var ids = $("#all_users").val();
$.ajax({
type:"POST",
url: base_url+"history/home/get_users",
data: "userid=" + ids,
success: function(result){
$("#m_ajax").html(result);
}
});
}
</script>
in your controller you can get the value of userid as post
$userid = $this->input->post('userid');
and you can perform other operations according.

HTML5 PHP AJAX upload: PHP not working

I'm trying to code my own php uploader so I can learn and understand how it all works. Trying not to use any libraries/plugins/API's. So basically I have the javascript stuff doin what it's supposed to be (i hope..). Now I'm stuck on the PHP. I want it to upload and save it as img/1.png. (not using any variables just to test it...). Here are my scripts. Keeping it very simple without any error checks just to get basic uploading working. Would this work for multiple files? May somebody guide me on what my PHP file should look like just for very basic (multi)file upload? Thanks!
album_create.js
$(document).ready(function() {
$('#album_create').submit(function() {
var file = document.getElementById('album-files').files[0]; //Files[0] = 1st file
var reader = new FileReader();
reader.onload = function(f) {shipOff(f);};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsText(file, 'UTF-8');
return false;
});
});
function shipOff(event) {
var result = event.target.result;
var fileName = document.getElementById('album-files').files[0].name; //Should be 'picture.jpg'
console.log(fileName);
$.post('ajax/album_create.php', { data: result, name: fileName }, function(data){console.log(data);});
return false;
}
ajax/album_create.php
$data = $_POST['data'];
move_uploaded_file($data[0], 'img/1.png');
you are posting:
data: result, name: fileName
but album_create.php expecting:
$data = $_POST['data'];
$fileName = $_POST['fileName'];
$fileName = $_POST['fileName']; should be: $fileName = $_POST['name'];

Categories