title: XML File Downloading in Spring MVC
body: <p>I need to download xml file through spring mvc and need my application to navigate to some another jsp page after successful download using ModelAndView. While downloading file I am getting error that</p>
  
  <blockquote>
    <p>java.lang.IllegalStateException: getOutputStream() has already been called for this response</p>
  </blockquote>
  
  <p>Could you please help me regarding this.</p>
  
  <pre><code>@RequestMapping(value="/download",method = RequestMethod.GET)
  public ModelAndView downloadXmlFile(HttpServletRequest request,
          HttpServletResponse response) throws IOException {
  
     servletcontext context = request.getsession().getservletcontext()
  
      File downloadFile = new File("c:\\abc.xml");
      FileInputStream inputStream = new FileInputStream(downloadFile);
  
      // get MIME type of the file
      String mimeType = context.getMimeType(fullPath);
      if (mimeType == null) {
          // set to binary type if MIME mapping not found
          mimeType = "application/octet-stream";
      }
      System.out.println("MIME type: " + mimeType);
  
      // set content attributes for the response
      response.setContentType(mimeType);
      response.setContentLength((int) downloadFile.length());
  
      // set headers for the response
      String headerKey = "Content-Disposition";
      String headerValue = String.format("attachment; filename=\"%s\"",
              downloadFile.getName());
      response.setHeader(headerKey, headerValue);
  
      // get output stream of the response
      OutputStream outStream = response.getOutputStream();
  
      byte[] buffer = new byte[4096];
      int bytesRead = -1;
  
      // write bytes read from the input stream into the output stream
      while ((bytesRead = inputStream.read(buffer)) != -1) {
          outStream.write(buffer, 0, bytesRead);
      }
  
      inputStream.close();
      outStream.close();
  
      return "Success";
  }
  </code></pre>