title: Download .csv with Play! framework
body: <p><strong>EDIT</strong></p>
  
  <p>From what I have learned (from comments by nico_ekito) it is not possible to use ajax call to download a file. The solution is to create a hidden <code>&lt;iframe&gt;</code> that will download the file, described <a href="https://stackoverflow.com/questions/676348/allow-user-to-download-file-using-ajax">here</a>.</p>
  
  <hr>
  
  <p><strong>Problem</strong>:
  The browser doesn't show download dialog. Any browser - ff, opera, chrome, safari, ie.</p>
  
  <p>I read the <a href="https://github.com/playframework/Play20/wiki/JavaStream" rel="nofollow noreferrer">docs</a> about serving files, found <a href="https://stackoverflow.com/questions/2868225/not-being-prompted-to-download-csv-file">this question</a> and, based on this, wrote:</p>
  
  <pre><code>Controller.response().setContentType("text/csv");
  Controller.response().setHeader("Content-Disposition", "attachment;filename=public/export/filename.csv");
  Controller.response().setHeader("Cache-control", "private");
  
  return ok(CSV.export(data, filename));
  </code></pre>
  
  <p>Where <code>CSV</code> is a class:</p>
  
  <pre><code>public class CSV{
      public static File export(Map&lt;String, String&gt; data, String filename){
          String csv = data.get("data[saveMe]");
  
          try {
              BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("public/export/" + filename), "UTF-8"));
              bw.write(csv);
              bw.newLine();
              bw.flush();
              bw.close();
          }catch(UnsupportedEncodingException e){}
          catch(FileNotFoundException e){}
          catch(IOException e){}
  
          File downloadMe = new File("public/export/" + filename);
  
          return downloadMe;
      }
  }
  </code></pre>
  
  <p>On client side, I use <code>dojo</code> to send <code>POST</code> request (I also tried with <code>GET</code>, result is the same):</p>
  
  <pre><code>xhr.post({
      url: '/exportData/',
      content: {
          saveMe: str
      }
  }).then(function(response){
      //do sth 
  });
  </code></pre>
  
  <p>Response headers look like that:</p>
  
  <pre><code>Cache-Control       private
  Content-Disposition attachment;filename=public/export/filename.csv
  Content-Type        text/csv
  Transfer-Encoding   chunked
  </code></pre>
  
  <p><code>POST</code> tab in firebug shows proper data in proper csv format. To format data with csv style I use <a href="http://dojotoolkit.org/reference-guide/1.8/dojox/grid/EnhancedGrid/plugins/Exporter.html#prerequisites" rel="nofollow noreferrer">dojox/grid/enhanced/plugins/exporter/CSVWriter</a></p>