Function Repository Resource:

FileDownloadResponse

Source Notebook

Generate an HTTP response that prompts the browser to download as a given file name

Contributed by: Richard Hennigan (Wolfram Research)

ResourceFunction["FileDownloadResponse"][expr,"filename"]

generates an HTTPResponse that informs the browser that the content should be downloaded as the given filename.

ResourceFunction["FileDownloadResponse"][expr,"filename",fmt]

uses fmt as the ExportForm.

ResourceFunction["FileDownloadResponse"][expr,"filename",fmt,metadata]

includes metadata as part of the HTTPResponse.

Details and Options

ResourceFunction["FileDownloadResponse"] is usually stored in a CloudObject or specified as the result in an APIFunction or FormFunction.
The value for metadata in ResourceFunction["FileDownloadResponse"][expr,"filename",fmt,metadata] is an Association including the following possible elements:
"StatusCode"200HTTP status code
"ContentType""text/html"MIME type for content
"Cookies"{}cookies to handle (using CookieFunction)
"Headers"{}a list of rules giving HTTP response headers
Properties of the resulting HTTPResponse object can be accessed using HTTPResponse[]["prop"].
Possible properties include all metadata items, together with:
"Body"response body as a string
"BodyByteArray"response body as a ByteArray object
"BodyBytes"response body as a list of byte values
"CharacterEncoding"character encoding in the response body (e.g. "UTF8")
"Properties"list of available properties
"StatusCodeDescription"plain text description of status code
ResourceFunction["FileDownloadResponse"] has the following options:
CharacterEncodingAutomaticcharacter encoding to apply to the response
CachePersistenceInheritedhow long to keep server-side cached versions of computations that are done
"ContentType"Automaticspecify a content-type header
The setting CharacterEncoding"enc" specifies that the body in the resulting HTTPResponse[body,] should be encoded using the encoding enc before being returned from a server as an HTTP response.
The setting CharacterEncodingNone specifies that no change should be made to body before returning it.
The Automatic setting for the CharacterEncoding option will use an encoding given from the "ContentType" metadata property if it includes a charset specification (as in "text/html; charset=latin1"). It will also use an encoding from the "CharacterEncoding" metadata property. If no encoding is otherwise given, then the "UTF8" encoding is used for text-based MIME types and None for other MIME types.
If a specific encoding is given for the CharacterEncoding option, and the "ContentType" metadata property is a text-based MIME type, a charset specification will be automatically added to indicate the encoding to browsers.

Examples

Basic Examples (3) 

Generate an HTTPResponse:

In[1]:=
ResourceFunction[
 "FileDownloadResponse"][{{1, 2, 3}, {4, 5, 6}}, "download.csv"]
Out[1]=

The content disposition is set with the given file name:

In[2]:=
%["Headers"]
Out[2]=

Specify a format:

In[3]:=
ResourceFunction[
 "FileDownloadResponse"][{{1, 2, 3}, {4, 5, 6}}, "download.data", "Package"]
Out[3]=

Provide additional metadata for the HTTPResponse:

In[4]:=
ResourceFunction[
 "FileDownloadResponse"]["I'm a teapot", "download.txt", Automatic, <|
  "StatusCode" -> 418|>]
Out[4]=

Scope (3) 

The MIME type is determined automatically from the file name when a format is not explicitly given:

In[5]:=
ResourceFunction["FileDownloadResponse"][{{1, 2, 3}, {4, 5, 6}}, "download.csv"]["ContentType"]
Out[5]=
In[6]:=
(* Evaluate this cell to get the example input *) CloudGet["https://www.wolframcloud.com/obj/fa304c2f-9c6c-4c96-b174-475940f498e1"]
Out[6]=
In[7]:=
(* Evaluate this cell to get the example input *) CloudGet["https://www.wolframcloud.com/obj/a94dbb3b-300f-46c3-9055-1c9d3fb50668"]
Out[7]=

It defaults to text if unknown:

In[8]:=
ResourceFunction["FileDownloadResponse"][{{1, 2, 3}, {4, 5, 6}}, "download"]["ContentType"]
Out[8]=

A format can be given explicitly to override the content type:

In[9]:=
ResourceFunction["FileDownloadResponse"][{{1, 2, 3}, {4, 5, 6}}, "download", "CSV"]["ContentType"]
Out[9]=

Specify custom headers:

In[10]:=
ResourceFunction[
 "FileDownloadResponse"]["Hello world", "hello.txt", Automatic, <|
  "Headers" -> {"My-Header" -> "Does it work?"}|>]
Out[10]=
In[11]:=
%["Headers"]
Out[11]=

Options (3) 

CharacterEncoding (1) 

Specify a character encoding:

In[12]:=
ResourceFunction["FileDownloadResponse"]["Hello world", "hello.txt", CharacterEncoding -> "UTF-8"]
Out[12]=
In[13]:=
ResourceFunction["FileDownloadResponse"]["Hello world", "hello.txt", CharacterEncoding -> "ASCII"]
Out[13]=

CachePersistence (1) 

Deploy a file download that is cached for 3 seconds:

In[14]:=
obj = CloudDeploy[
  Delayed[ResourceFunction["FileDownloadResponse"][
    DateString[{"Time", ".", "Millisecond"}], "date.txt", CachePersistence -> 3]]]
Out[14]=
In[15]:=
Table[Pause[1]; URLRead[obj, "Body"], 5]
Out[15]=

ContentType (1) 

Specify a MIME type for the response:

In[16]:=
ResourceFunction["FileDownloadResponse"][Range[10], "download", "ContentType" -> "application/octet-stream"]
Out[16]=

Applications (2) 

Generate an HTTPResponse from a FormFunction for downloading an image:

In[17]:=
FormFunction[{"image" -> ExampleData["TestImage"][[All, 2]]},
 ResourceFunction["FileDownloadResponse"][
   ExampleData[{"TestImage", #image}], #image <> ".png"] &
 ]
Out[17]=

Deploy it to the cloud:

In[18]:=
CloudDeploy[%]
Out[18]=

Possible Issues (2) 

Specifying the content type in the metadata will override the format:

In[19]:=
ResourceFunction[
 "FileDownloadResponse"][{{1, 2, 3}, {4, 5, 6}}, "download.csv", "CSV", <|"ContentType" -> "text/html"|>]
Out[19]=

Providing a content disposition header in the metadata can override the given file name:

In[20]:=
ResourceFunction[
 "FileDownloadResponse"][{{1, 2, 3}, {4, 5, 6}}, "download.csv", "CSV", <|
  "Headers" -> {"content-disposition" -> "attachment; filename=override.csv"}|>]
Out[20]=
In[21]:=
%["Headers"]
Out[21]=

Version History

  • 2.0.0 – 28 August 2019
  • 1.0.0 – 08 February 2019

Related Resources

License Information