Discussions

Web tier: servlets, JSP, Web frameworks: downloading CSV

  1. downloading CSV (2 messages)

    Hi guys,

    I am trying to download a generated CSV file from the server side to the client browser. However, my browser keeps showing the CSV's content and no file dialog box appears. Any idea how i can have the file dialog box to appears?

    Please help. Thanks in advance.

    Here is my code:

    ServletOutputStream os = null;
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try
    {

      os = response.getOutputStream();
      String content = "test,test,test,test,test,test,test,test\ntest,test,test,test,test,test,test,test";
      //response.setContentType("application/msexcel");
      //response.setHeader("Content-disposition","attachment; filename=test.csv");
      
      
      //response.resetBuffer();
      //response.setContentType("application/octet-stream");
      response.setContentType ("application/x-msexcel");
      response.setHeader("Cache-Control", "no-cache");
      response.setHeader("Content-Disposition","attachment;filename=test.ppp");
      response.setHeader("Content-Length", String.valueOf(content.getBytes().length));
      
      
      //String FileUrl="http://www.adobe.com/aboutadobe/careeropp/pdfs/adobeapp.pdf";
      //URL u=new URL(FileUrl);
      //bis=new BufferedInputStream(u.openStream());
      
      
      ByteArrayInputStream bais = new ByteArrayInputStream(content.getBytes());
      bis=new BufferedInputStream(bais);
      
      bos=new BufferedOutputStream(os);
      
      byte[] buff=new byte[2048];
      int bytesread;
      
      while((bytesread=bis.read(buff,0,buff.length)) != -1) {
        bos.write(buff,0,bytesread);
      }

    } catch(Exception e) {
      System.out.println(e.toString());
    } finally {
      if (bis != null) {
        bis.close();
      }
      if (bos != null) {
        bos.close();
      }
    }

    Threaded Messages (2)

  2. downloading CSV[ Go to top ]

    Try setting the content type to application/pdf.

    Regards,
    Abhishek Bhargava
  3. thanks.[ Go to top ]

    Its working once i have the following:

    ...
    os = response.getOutputStream();
      String content = "test,test,test,test,test,test,test,test\ntest,test,test,test,test,test,test,test";
      response.setContentType("application/octet-stream");
      response.setHeader("Content-disposition","attachment; filename=test.csv");
    ...
    Thanks for the help :)