views:

44

answers:

4

I have a standard restful rails application.

format.html { @users = User.find(:all, :limit => 10)}
format.csv { @users = User.find(:all, :limit => 10) }

When the url is

http://localhost:3000/users.csv

I get a file with name users.csv .

However if the url is

http://localhost:3000/users?format=csv

then the file I get has name users. I would like to have file name to be users.csv .

+2  A: 

This is the browser's default file naming coming into play. The browser doesn't know anything about the meaning of the format parameter. It just sees the resource being accessed is called 'users', so it defaults to that file name.

In the former example, the resource being requested is called users.csv, so it uses that as the default file name.

You may also want to look into the Content-Disposition HTTP header. This will cause the browser to prompt the user to save the file with a specified file name as the default (the user is free to change that though), instead of displaying the file in the browser. Thus, you could have your resource be http://localhost:3000/users?format=csv, but default the file name to foo.csv with this header:

Content-disposition: attachment; filename=foo.csv

Check out this Microsoft link for some more information. The concept is the same for rails as it is for any HTTP technology.

pkaeding
A: 

Set the Content-Disposition response header to attachment; filename=users.csv.

Ignacio Vazquez-Abrams
A: 

You can send a Content-disposition header with a filename parameter to suggest a default filename to the user. For example, Content-dispostion: attachment; filename=users.csv.

By default, the browser will usually use the last component of the path portion of the URL (the part before the query, which begins with ?) as the filename. Some browsers, like Safari, will also add an extension based on the MIME type if they don't believe the current extension matches the MIME type, and they know what extension to use.

Brian Campbell
A: 

This is recognizeable as default MSIE behaviour. It ignores the filename parameter of the Content-Disposition header (if you have set any yourself). You'll really need to append the full filename as pathinfo of the URL if you want to get it to work in that browser as well. All other browsers respects the Content-Disposition header as expected.

BalusC