Erik S
Erik S

Reputation: 13

How do I allow download of a file in drupal?

I have a report that I want to allow users to pull the current data for into a downloadable .csv file.

I am currently using unmanaged_write_submit but this just prints the csv to the screen and users would have to right click and save as. I want to make it as easy as possible, by allowing the actual file to be downloaded through a button click.

$page['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Download Report',
    '#submit' => array('test_unmanaged_write_submit'), 
    );


function test_unmanaged_write_submit($form, &$form_state) {
    //$data is pulling the .csv/query data
    $data = get_array_data($form,&$form_state); 
    $destination = !empty($form_state['values']['destination']) ? $form_state['values']['destination'] : NULL;

    // With the unmanaged file we just get a filename back.
    $filename = file_unmanaged_save_data($data, $destination, FILE_EXISTS_REPLACE);
    if ($filename) {
        $url = file_create_url($filename);
        $_SESSION['file_example_default_file'] = $filename;
        drupal_set_message(t('Saved file as %filename (accessible via !url, uri=<span id="uri">@uri</span>)', array(
       '%filename' => $filename,
       '@uri' => $filename,
       '!url' => l(t('this URL'), $url),
    )));
    }
    else {
        drupal_set_message(t('Failed to save the file'), 'error');
    }
}

But this only provides a link to a webpage that displays the .csv on the screen. Is there another drupal function or way to force a file download in php?

Upvotes: 1

Views: 1790

Answers (1)

tobbr
tobbr

Reputation: 2186

It's been a while since I've used Drupal but based on the answer provided here.

You can set the redirect variable in the $form_state array to the URL of your file. So basically just take the $url from your call to file_create_url and stick it into the redirect:

$form_state['redirect'] = $url;

If that doesn't do the trick you can do it with pure PHP as described here.

Upvotes: 1

Related Questions