Export csv file using stream with Play 2.1

I would like to allow the client to download the csv file containing the data from the ResultSet. I am using the java API (PLAY! 2.1).

My solution works, but is not used when the ResultSet contains a huge amount of data.

In my controller:

ResultSet rs = st.executeQuery(sql); String filename = ""; filename = createCSV(rs);. response().setContentType("text/csv"); response().setHeader("Content-disposition","attachment; filename="+"export.csv"); return ok(new java.io.File("D:\\UTILIS~1\\user\\AppData\\Local\\Temp\\"+filename)); 

createCSV method:

 public static String createCSV(ResultSet _resultSet) { String filename = ""; try{ ResultSetMetaData meta = _resultSet.getMetaData(); // CSV file creation File tempDir = new File(System.getProperty("java.io.tmpdir")); System.out.println(System.getProperty("java.io.tmpdir")); File tempFile = File.createTempFile("test", ".csv", tempDir); filename = tempFile.getName(); FileWriter fileWriter = new FileWriter(tempFile, true); System.out.println(tempFile.getAbsolutePath()); BufferedWriter bw = new BufferedWriter(fileWriter); for(int i = 1; i <= meta.getColumnCount(); i++) { String columnLabel = meta.getColumnName(i); bw.write(columnLabel + "|"); } bw.write("\r\n"); while(_resultSet.next()) { for(int i = 1, count = meta.getColumnCount(); i <= count; i++){ if (_resultSet.getObject(i) == null) bw.write("null|"); else bw.write(_resultSet.getObject(i).toString() + "|"); } bw.write("\r\n"); } bw.close(); tempFile.deleteOnExit(); } catch(Exception e){ e.printStackTrace(); } return filename; } 

To save memory, how can I write a file and send it to the user using the stream.

I think I need to use Chunks, but I'm not sure how to do this.

Any samples, tips?

+4
source share
3 answers

In the documentation you can find an example of a fragmented answer:

http://www.playframework.com/documentation/2.1.1/JavaStream

You can send csv content during its creation.

+1
source

The Ok method accepts a byte array as a parameter

So, get an array of bytes of the file content and try

return ok(s.toByteArray()).as("application/octet-stream");

See this for an array of file bytes.

+1
source

1) Get the output stream from the response

2) Pass this output stream to the createCSV method and write to it directly

You can also pin results by decorating the output stream with ZipOutputStream.

Note: there is no need to create a temporary file.

0
source

Source: https://habr.com/ru/post/1484404/


All Articles