Quantcast
Channel: web – Imran Tariq's Blog
Viewing all articles
Browse latest Browse all 33

File download code through stream, Java

$
0
0

Sometimes we may need to give support in our application to download a file. For example if you want to convert String to a file and wants to get a downloadable dialog in browser to download file.

To achieve this following code will help you. This example code will work for servlets, struts, Spring MVC etc. You just need to take care of response headers. This code is helpful for any type of file download if you change response.setContentType(“application/xml”); to any other file format and change file name too. If you note then you will see that there some special headers that are set in response object.

@RequestMapping(value = "/urlhere", method = RequestMethod.POST)

public ModelAndView urlhere(HttpServletRequest request, HttpServletResponse response) throws Exception {

    ModelAndView mav = new ModelAndView();

       String str= "string to convert into xml file and then download that file through browser dialog.";

        //set response headers
        response.setHeader("Pragma", "public");
        response.setHeader("Expires", "0");
        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.setHeader("Content-type", "application-download");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        response.setHeader("Content-Transfer-Encoding", "binary");
        response.setContentType("application/xml");

        Writer writer = response.getWriter();
        writer.append(str);
        writer.close();

       mav.setViewName("viewname");

      return mav;

    }

You may want to change some mapping values, header values or viewName so just change those accordingly.


Viewing all articles
Browse latest Browse all 33

Trending Articles