I’m using File.open to create a .csv file on the fly.
But what I need to do is set the Content-Type of the file to binary/octet-stream so that the browser will automatically download it instead of just displaying the contents of it in the browser.
The file itself is created locally and then uploaded to Amazon S3.
Short Answer
There is no way to specify a
Content-Typevalue in the filesystem when you create your file. In fact, this is probably not the best way to achieve your goal.In order to suggest that a browser download a file rather than displaying it, you can leave
Content-Type: text/csvand add the headerContent-Disposition: attachmentorContent-Disposition: attachment; filename=<your custom filename>.csvto change the filename in the “Save As…” dialog.Setting
Content-Dispositionusing Paperclip and AWS::S3To set the
Content-Dispositionheader using Paperclip, you can add a key to yourhas_attached_filedefinition:s3_headers.Content-Type issues
By default, a file with the extension
.csvshould be classified as atext/csvfile. You can check this withMime::Type.lookup_by_extension('csv').to_s # => "text/csv". If this is not the case, you can add text/csv as a custom mime-type by creating aconfig/initializers/mime_types.rbfile and adding:However, this should almost always not be the case (unless Windows does something funky with content types; I’ve only tested in Linux).
Examples
I’ve put up two examples that you can check. The first is a CSV file uploaded with a
text/plainmime-type which forces the browser to show it in-browser without downloading (my browser downloadedtext/csvfiles).https://s3.amazonaws.com/stackoverflow-demo/demo.csv
The second also has a mime-type of
text/plain, but I added a headerContent-Disposition: attachment; filename="mycustomname.csv"https://s3.amazonaws.com/stackoverflow-demo/demo-download.csv
You’ll notice that the first link is displayed in browser, while the second link is downloaded with the custom name
mycustomname.csv.To learn why, look at the headers using
curl -I.versus
Note: unrelated headers were removed.