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.
The filename should be a quoted string. (According to Section 19.5.1 of RFC 2616)
response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With