开发者

Redirecting webpage to a file

Suppose a webpage that presents a table, but with an option to download it as an Excel sheet. The option is presented as a button that submits a form (containing the required parameters to create the same report, but for Excel).

<form action="makereport.blah">
<!-- Some parameters -->
<input type="button" value="Export to Excel" onClick="submit();"/>
</form>

The final step remains to direct the browser to the created Excel sheet.

I see three possibilities:

  1. In the "action" page of the form, with the OnLoad event: rewrite in JavaScript the URL to the created file path and reload the page

  2. In the HTTP header: Redirect to the url of the file (with the Redirect command)

  3. Using an iframe, where src is the t开发者_运维知识库arget file

Those seem a bit hackish, but I've used them in the past. How is this normally done?

(As a note, the language I'm using to generate the HTML (and Excel sheet) is an in-house solution. So if PHP has something for that, I would just have to port it).


Possibility 4 (the right one): the PHP script this form points to should send a Content-type: application/vnd.ms-excel header then the contents of the Excel file. If it's an actual file on disk, use readfile, otherwise just echo the Excel data straight out. If you want to specify a filename for download, you can also send a Content-Disposition: attachment; filename='filename' header.


The script/code that handles the posting of the form (server side) can generate the Excel spreadsheet. Then instead of replying with an HTML response (or some kind of redirect) you can instead return the spreadsheet directly (with the correct HTTP headers that would be sent if the file was loaded directly).

An example in PHP:

<?php

// generate spreadsheet in file
$file = do_something_to_generate_spreadsheet();

// specifies it is an excel spreadsheet response
header('Content-Type: application/vnd.ms-excel'); 
header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename="' . $file . '"'); // filename
header('Content-Length: ' . filesize($file)); // length

readfile($file); // sends file to client

?>


Why have a second page at all? Make makereport.blah the xls file itself instead of another HTML document.


you can use DATAURI scheme in new file to insert file in base64 mode. i'll make a script tonight.


Using base64 code from webtoolkit.info and disassembling an XML/XLS file i have tried make a script to force to download a file made in the air. I make a windows object and when this will open, then insert XML/XLS code codified with base64. this method is a hack of dataURI. I have not put a name when the file download. I tried on google chrome. here an jsfiddle of file.

Thanks for your interest.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜