Welcome Guest, Not a member yet? Register   Sign In
Download file only when click on link in foreach loop
#3

(02-12-2017, 11:55 PM)Wouter60 Wrote: You're talking about a preview button. Where is it? I can't find it in your view.

To force download of the links that are being displayed by the foreach loop, you need a slightly different approach.
Replace the '<a> ... </a>' part with:
PHP Code:
<?php echo anchor('preview/downloadfile/' $attachment['id'], $attachment['file_name']); ?>

Instead of $attachment['id'], it may be even safer to work with something like $attachment['code'], which is a unique 32 character random string (see String Helper). That way, you neither reveal the entire path where your attachments are stored, nor the id of the attachments in your database.

You will have to adjust the preview/downloadfile method to the new situation. It will get the id or code of the file as a parameter. Use that to look up the path in your database. Use that to actually force downloading the file. By the way, it's good practice to keep all your methods (in controllers) lower case only.

On more tip: you can use the alternative php syntax in your views to improve readability:
PHP Code:
<?php foreach ($attachments as $attachment) : ?>
   //...
<?php endforeach; ?>


On the view I have now changed the attachments to like and on my controller function I have added exit; is that OK.

Seems to download now.

PHP Code:
<div class="row">
<?
php foreach ($attachments as $attachment) {?>
<div class="col-lg-2 col-md-2 col-sm-2 col-xs-12">
<?php if ($attachment['type'] == 'php') {?>

<p class="text-center">
<a href="<?php echo base_url('preview/downloads/' $attachment['attachment_id'] .'/'$attachment['attachment_name']);?>">
<img  class="img-thumbnail" style="cursor: pointer;" width="100%" height="110" src="<?php echo base_url('assets/images/icons/attachment_icons/1486989423_php.png');?>" id="download_<?php echo $attachment['attachment_id'];?>">
</p>

<p class="text-center">
<?php echo $attachment['file_name'];?>
</p>


</div> 

And on controller function


PHP Code:
public function downloads() {
      force_download(FCPATH 'uploads/' $this->uri->segment(4) . '/' $this->uri->segment(5), NULL);

     exit;

There's only one rule - please don't tell anyone to go and read the manual.  Sometimes the manual just SUCKS!
Reply


Messages In This Thread
RE: Download file only when click on link in foreach loop - by wolfgang1983 - 02-13-2017, 01:18 AM



Theme © iAndrew 2016 - Forum software by © MyBB