开发者

How to make a file 'download' when clicked in Windows IE

开发者 https://www.devze.com 2023-02-09 07:17 出处:网络
I have a button in a form tag that generates a CSV file and prompts a download when a user clicks it.

I have a button in a form tag that generates a CSV file and prompts a download when a user clicks it.

When I try to accomplish this in IE, IE tries to open the file with IE which it shouldn't. I just want it to downl开发者_C百科oad the file.

My HTML :

<FORM accept-charset="UTF-8" method="post" action="/generate_csv?calc[]total_interest=189.08">
  <DIV style="margin: 0px; padding: 0px; display: inline;"><INPUT name="utf8" value="✓" type="hidden">
    <INPUT name="authenticity_token" value="4o1dEDoFbbDoc3scpnhDaQpPtpFM5NitTOrYQA0AU5k=" type="hidden">
  </DIV>
  <INPUT id="print_csv" name="commit" value="Print CSV" type="submit">
</FORM>

My Rails Controller :

headers['Content-Disposition'] = "attachment;"
send_data(csv_string,
  :type => 'text/csv; charset=utf-8; header=present; disposition=attachment',
  :filename => @filename,
  :disposition => 'attachment')

Any ideas how to accomplish this?


I would try the following. In your controller, when you generate the CSV file you are probably sending it using send_data or send_file. Is that correct? If so, you probably need to set the disposition as 'attachment' instead of simply sending the file or the data. For example:

send_data @csv, :type => 'text/csv', :disposition => 'attachment', :filename => 'generate_csv.csv'

or

send_file '/path/to.csv', :type => 'text/csv', :disposition => 'attachment'

Another thing you can do is modify your routes to include a format. For example:

match 'generate_csv.csv' => 'csv#generate_csv'

You can convert your post request to a get request like this:

<%= link_to "Print CSV", '/generate_csv?calc[]total_interest=189.08' %>


The program generating the CSV needs to add an HTTP header for Content-Disposition:

 Content-Disposition: attachment; filename=<file name.ext>

See http://www.jtricks.com/bits/content_disposition.html.


To hint a browser that it should download a file, make sure you send the Content-Disposition: attachment header from your application.

0

精彩评论

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