Pergunta

I am generating pdf's based on a user's choice and zipping them together in a servlet. I give the zip folder a file name, but when I use the web app to download the zip folder, the zip folder's file name is not always the file name that I gave to it. When I download the folder, it either (1) has the correct name (happens most of the time) or (2) it has the name of the servlet without the .zip suffix. In either case, the contents of the folder are correct. Scenario (2) is only happening in two particular cases. (i.e., when trying to bundle specific pdfs together.)

During the debugging process, I checked to make sure that the file name is indeed correct. Also, no exceptions are being thrown, so I cannot even begin to understand what is wrong.

Code

    java.util.zip.ZipOutputStream myZOS = new java.util.zip.ZipOutputStream(response.getOutputStream());

    java.util.List<String> cIDs = Arrays.asList(request.getParameterValues("cID"));
    String rID = request.getParameter("rID");
    String rName = "";
    String cNames = "";

    for(Integer i = 0; i < cIDs.size(); i++)
    {
        if(!cNames.equals(""))     //separate names with _
            cNames += "_";

        Foo myFoo = new Foo(Integer.valueOf(rID),Integer.valueOf(cIDs.get(i)));
        rName = myFoo.getName();
        cNames += myFoo.getCID();
        PDFDoc myPDFDoc = new PDFDoc(myFoo, request.getServerName());
        java.util.zip.ZipEntry myZE = new java.util.zip.ZipEntry(myPDFDoc.getFilename());
        myZOS.putNextEntry(myZE);
        myZOS.write(myPDFDoc.getPDF());
    }

    logger.log(java.util.logging.Level.SEVERE, "rName: ".concat(rName).concat("; cNames: ").concat(cNames));  //correct name

    response.setContentType("application/zip");

    response.setHeader("Content-disposition", "attachment; filename=\"" + rName + "_" + cNames + ".zip\"");
    response.getOutputStream().flush();
    myZOS.close();
Foi útil?

Solução

You have to do response.setContentType("application/zip") before opening the outputstream. Otherwise the servlet doesn't know what kind of content it is and will just return the servlet's name as the file name.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top