Announcement Announcement Module
Collapse
No announcement yet.
Controller to download file Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Controller to download file

    I need to download a excel file using a controller with the excel file name as save as. please suggest me the appropriate controller and sample code

  • #2
    You can just use any ordinary controller. Use an ExcelView as the view. The reference documentation provides more info here!

    rgds,
    Alef Arendsen

    Comment


    • #3
      something like

      Code:
      String filename = .............
      byte[] content = ...............
      
      String mimetype = this.getServletContext().getMimeType(filename);
      response.setContentType(mimetype);
      response.setContentLength(content.length);
      response.setHeader("Content-Disposition","attachment; filename=\"" + filename +"\"");
      FileCopyUtils.copy(content , response.getOutputStream());
      return null;
      the Content-Disposition will cause the browser to download it rather than display it.

      Comment


      • #4
        This is my controller in order to download a generic file.
        In the .jsp file you can have something like:
        <a href=".../download.html?file=/pathname/myfile.ext">myfile.ext</a>
        my controller is:
        public class DownloadController implements Controller {

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

        ServletContext servletContext = request.getSession()
        .getServletContext();

        String file = request.getParameter("file");
        String fileName = file.substring(file.lastIndexOf("/") + 1);

        File uFile = new File(servletContext.getRealPath("/"), file);
        int fSize = (int) uFile.length();

        if (fSize > 0) {

        BufferedInputStream in = new BufferedInputStream(
        new FileInputStream(uFile));
        String mimetype = servletContext.getMimeType(file);

        response.setBufferSize(fSize);
        response.setContentType(mimetype);
        response.setHeader("Content-Disposition", "attachment; filename=\""
        + fileName + "\"");
        response.setContentLength(fSize);

        FileCopyUtils.copy(in, response.getOutputStream());
        in.close();
        response.getOutputStream().flush();
        response.getOutputStream().close();
        } else {
        response.setContentType("text/html");
        PrintWriter printwriter = response.getWriter();
        printwriter.println("<html>");
        printwriter.println("<br><br><br><h2>Could not get file name:<br>" + file + "</h2>");
        printwriter.println("<br><br><br><center><h3><a href='javascript: history.go(-1)'>Back</a></h3></center>");
        printwriter.println("<br><br><br>&copy; webAccess");
        printwriter.println("</html>");
        printwriter.flush();
        printwriter.close();
        }

        return null;
        }
        }
        In this way I can overload the Internet Explorer standard behaviour that doesn't permit to open the "Save" dialog for already know mime types as pdf, jpeg, gif, ....

        Comment


        • #5
          I too need to download a file. I have used the approach stueccles has suggested and it works fine on firefox but not on internet explorer (v6)!

          When I click on the to be downloaded file I get a the familiar 'save or open file' window. If I choose to save the file everything works fine. However, when I choose to open the file, I get error messages like:
          - "This file could not be found" (for word files)
          - "The compressed (zipped) folder is invalid or corrupted
          - "Cannot find the file" (for txt files)

          This is some code from the Controller:

          httpServletResponse.setBufferSize(fileSize);
          httpServletResponse.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
          httpServletResponse.setContentType(contentType);
          httpServletResponse.setContentLength(fileSize);
          FileCopyUtils.copy(fileBytes, httpServletResponse.getOutputStream());
          return null;

          fileBytes is a byte[] that was stored as a blob in the database.

          Any help is highly appreciated!

          Comment


          • #6
            Do you check some login requirements before your download starts?

            In ie, when you set the content disposition to be inline, the browser will do 2 requests, where the 2nd request will be sent without cookies. So if there is some authentication requirement that is saved in the cookies, the file will not be sent. Also make sure that the download url ends with the extension that IE expects and knows otherwise it will show the binary format in the browser without starting the application to handle the bytes. So my download urls always end with a specific parameter IE=pdf or something like that

            HtH
            Ronald

            Comment


            • #7
              Any follow-ups on this issue?
              I have exactly the same problem when trying to download the excel file, and I did set the "Content-disposition" to "attachment".
              Thanks.

              -JJ

              Comment


              • #8
                I have the seem problem. I use tomcat 5.5.
                Finally I found that it's because I turned on the compression option in the server.xml. If I turned off it, the execl can be download properly.

                If I still want to zip the excel file, how to let the client side know it's zipped excel file?

                Comment


                • #9
                  Check the cache settings. I've seen IE agresively enforce the no-cache directive such that it deletes the file before you can open it.

                  Comment


                  • #10
                    Try setting the following header values in the response:

                    Code:
                    response.setHeader("Cache-Control", "no-cache");
                    response.setHeader("Pragma", "no-cache");
                    response.setDateHeader("Expires", 0);

                    Comment


                    • #11
                      How to download data into excel .

                      Hi all genius people,

                      Can you please tell me when i click on a image it should go to a controller which is doing work of downloading data in the excel.

                      My controller is fine but I am not getting how to map that click of image with
                      controller,

                      In Jsp ::: <a href="download"><img src ="images/download.jpg" alt="Download" border="0"/> </a>

                      In Servlet-xml mapping i have done as ::: I am using one service class that is OK. Controller name is ExcelController.

                      <bean id="download" class="com.infosys.kneuron.handler.ExcelController ">
                      <property name="peopleService" ref="peopleService"/>
                      </bean>


                      Plz tell me how I can implement it.

                      Thanks in advance.

                      Comment


                      • #12
                        You can have a look at the blog post:

                        http://me-ramesh.blogspot.com/

                        I think that would be helpful for all types of file downloads.

                        Thanks.

                        Comment


                        • #13
                          Hi David,

                          Did you get any clue on this. I'm facing the same problem. while downloading my file got corrupted.

                          Comment


                          • #14
                            Hi,

                            During download my file got corrupted. After struggling for a long time I came to know that it is being compressed by the GZIP filter whichi I have in web.xml. I had my own filter. So I put a exclude list and included download URLs in the web.xml to exclude filter for file downloadings.

                            Comment

                            Working...
                            X