I can’t download xls and doc files (old Office), the file is loaded, but it is empty and the message version pops up. With xlsx and docx everything is fine. Here is the code:

@GetMapping("getFileData/{id}") public void downloadFile(@PathVariable long id,HttpServletResponse response) { log.info("\n\nGET: /user/getFileData/"+id); File file = service.getFile(id); byte[]fileBytes = null; try(OutputStream os = response.getOutputStream()) { if(file.getType().split("/")[0].equals("image")){ fileBytes = service.loadImageFromFile(file.getFileName()); response.reset(); response.setContentType(file.getType()); response.getOutputStream().write(fileBytes); }else if(file.getFileName().split("\\.")[1].equals("pdf")){ fileBytes = service.loadFileFromFile(file.getFileName()); response.reset(); response.setContentType(file.getType()); response.getOutputStream().write(fileBytes); }else if(file.getFileName().split("\\.")[1].equals("xls")){ response.setHeader("Content-disposition","attachment; filename=" +file.getFileName().split("/")[2]); response.setContentType(file.getType()); HSSFWorkbook workbook = service.loadXLS(file.getFileName()); response.reset(); response.getOutputStream().write(workbook.getBytes()); }else if(file.getFileName().split("\\.")[1].equals("xlsx")){ response.setHeader("Content-disposition","attachment; filename=" +file.getFileName().split("/")[2]); response.setContentType(file.getType()); XSSFWorkbook workbook = service.loadXLSX(file.getFileName()); workbook.write(os); os.flush(); }else if(file.getFileName().split("\\.")[1].equals("doc")){ response.setHeader("Content-disposition","attachment; filename=" +file.getFileName().split("/")[2]); response.setContentType(file.getType()); HWPFDocument document = service.loadDOC(file.getFileName()); document.write(os); os.flush(); }else if(file.getFileName().split("\\.")[1].equals("docx")){ response.setHeader("Content-disposition","attachment; filename=" +file.getFileName().split("/")[2]); response.setContentType(file.getType()); XWPFDocument document = service.loadDOCX(file.getFileName()); document.write(os); os.flush(); } } catch (Exception e) { log.info("\n\n"+e.getMessage()); return; } log.info("\nReturn: OK"); } 
  • Not quite on the topic, but I advise you to look at Apache Commons IO , in particular on FilenameUtils.getBaseName() and FilenameUtils.getExtension() - V. Makhnutin
  • @ V.Makhnutin File - this is non-standard, and my class. - Nikolay Egorov

0