Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firefox cuts files, whose name contains spaces, in a Struts application

I am using the next class (simplified for the sake of understandability) to download images in a struts web application. It is working fine in every browser but firefox, which cuts names containing spaces. That it is to say: file with spaces.pdf gets downloaded in firefox as: file while in chrome, IE7 IE6 is downloaded as file with spaces.pdf.

public class Download extends Action {
    private static final int BUFFER_SIZE = 4096;    

    public ActionForward execute(ActionMapping mapping,
        ActionForm     form,
        HttpServletRequest request,
        HttpServletResponse response) throws Exception {
        String filename = "file with spaces.pdf";
        File file =  ... // variable containing the file;
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType(getMimeType(request, file));
        response.setHeader("Content-Type", getMimeType(request, file));
        response.setHeader("Content-Disposition","attachment; filename="+ filename);
        InputStream is = new FileInputStream(file); 
        sendFile(is, response);
        return null;
   }  

   protected String getMimeType(HttpServletRequest request, File file) {
        ServletContext application = super.servlet.getServletContext();
        return application.getMimeType(file.getName());
   }

   protected void sendFile(InputStream is, HttpServletResponse response) throws IOException {
       BufferedInputStream in = null;
       try {
            int count;
            byte[] buffer = new byte[BUFFER_SIZE];
            in = new BufferedInputStream(is);
            ServletOutputStream out = response.getOutputStream();
            while(-1 != (count = in.read(buffer)))
                out.write(buffer, 0, count);
            out.flush();            
       } catch (IOException ioe) { 
            System.err.println("IOException in Download::sendFile"); 
            ioe.printStackTrace();
       } finally {
            if (in != null) {
                try { 
                   in.close(); 
                } catch (IOException ioe) { ioe.printStackTrace(); }
            }   
       }
    }
}

Does anyone know about what is going on here? Note i am using firefox 3.0.3 under Windows Vista.

like image 677
Sergio del Amo Avatar asked Oct 07 '08 10:10

Sergio del Amo


2 Answers

The filename should be a quoted string. (According to Section 19.5.1 of RFC 2616)

response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
like image 70
Stephen Denne Avatar answered Oct 30 '22 00:10

Stephen Denne


URLEncode the filename?

Or at least substitute %20 for the space character.

(I don't know if this will work, but give it a try)

have you tried just putting quotes around the filename as well?

like image 45
JeeBee Avatar answered Oct 30 '22 00:10

JeeBee