servlets - Downloading a CSV File in Browser by using Java -


i'm trying add button on web application when clicked, downloads csv file (which tiny, 4kb in size).

i have button made , listener attached it. file ready. thing need create actual event downloads csv file when button clicked.

assuming "file" (which of type file) name of csv file i'm using, , it's ready go, method have far:

public void downloadcsv(httpservletrequest _request, httpservletresponse _response, logfiledetailcommand cmd) throws exception {      servletoutputstream outstream = _response.getoutputstream();      _response.setcontenttype("text/csv");        _response.setheader("content-disposition", "attachment; filename=data.csv"); } 

i realise i'm missing part writes file servletoutputstream part i'm stuck on. know class servletoutputstream extends class outputstream (http://docs.oracle.com/javaee/5/api/javax/servlet/servletoutputstream.html), , therefore has inherited "write" methods, in ideal world i'd "outstream.write(file);", can't seeing these "write" methods have either byte, byte[] , int parameters, , it's not possible pass file them.

what should pass file outstream?

(aside note: should add in "_response.setcontentlength();", , if so, parameters should put it?)

p.s. know after i'm finished outstream need flush and/or close it.

you can read csv file line-by-line, , write line on writer of httpserlvetresponse:

public class downloadcsvservlet extends httpservlet {  protected void doget(httpservletrequest request,         httpservletresponse response) throws servletexception, ioexception {      final file file = new file("/tmp/data.csv");      response.setcontenttype("text/csv");      response.setheader("content-disposition",             "attachment; filename=" + file.getname());      final bufferedreader br = new bufferedreader(new filereader(file));     try {         string line;         while ((line = br.readline()) != null) {             response.getwriter().write(line + "\n");         }     } {         br.close();     } }  } 

if use both reader , writer, character encoding handled (csv files text files encoding utf-8 example).

this solution streams, small portion of possibly large file in memory.


Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -