code_junkie

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

Nov 11th, 2011
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. public class Download extends Action {
  2. private static final int BUFFER_SIZE = 4096;
  3.  
  4. public ActionForward execute(ActionMapping mapping,
  5. ActionForm form,
  6. HttpServletRequest request,
  7. HttpServletResponse response) throws Exception {
  8. String filename = "file with spaces.pdf";
  9. File file = ... // variable containing the file;
  10. response.setStatus(HttpServletResponse.SC_OK);
  11. response.setContentType(getMimeType(request, file));
  12. response.setHeader("Content-Type", getMimeType(request, file));
  13. response.setHeader("Content-Disposition","attachment; filename="+ filename);
  14. InputStream is = new FileInputStream(file);
  15. sendFile(is, response);
  16. return null;
  17. }
  18.  
  19. protected String getMimeType(HttpServletRequest request, File file) {
  20. ServletContext application = super.servlet.getServletContext();
  21. return application.getMimeType(file.getName());
  22. }
  23.  
  24. protected void sendFile(InputStream is, HttpServletResponse response) throws IOException {
  25. BufferedInputStream in = null;
  26. try {
  27. int count;
  28. byte[] buffer = new byte[BUFFER_SIZE];
  29. in = new BufferedInputStream(is);
  30. ServletOutputStream out = response.getOutputStream();
  31. while(-1 != (count = in.read(buffer)))
  32. out.write(buffer, 0, count);
  33. out.flush();
  34. } catch (IOException ioe) {
  35. System.err.println("IOException in Download::sendFile");
  36. ioe.printStackTrace();
  37. } finally {
  38. if (in != null) {
  39. try {
  40. in.close();
  41. } catch (IOException ioe) { ioe.printStackTrace(); }
  42. }
  43. }
  44. }
  45. }
  46.  
  47. response.setHeader("Content-Disposition","attachment; filename="" + filename + """);
Add Comment
Please, Sign In to add comment