Download Excel file from server using servlets

I have an excel file on the server side. How can I display it on a client side browser using servlets?

Thanks in advance.

+4
source share
1 answer

To the point: just select its InputStream somehow ( FileInputStream is right) and write it in the OutputStream response with normal Java IO . That is basically all. You only need to make sure that you set the correct response headers so that the browser understands what to do with it. The Content-Type header instructs the webbrowser which file it wants the browser to know which application to use to open it.

Here is an example run:

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String filename = URLDecoder.decode(request.getPathInfo(), "UTF-8"); File file = new File("/path/to/files", filename); response.setHeader("Content-Type", getServletContext().getMimeType(file.getName())); response.setHeader("Content-Length", file.length()); response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\""); BufferedInputStream input = null; BufferedOutputStream output = null; try { input = new BufferedInputStream(new FileInputStream(file)); output = new BufferedOutputStream(response.getOutputStream()); byte[] buffer = new byte[8192]; for (int length = 0; (length = input.read(buffer)) > 0;) { output.write(buffer, 0, length); } } finally { if (output != null) try { output.close(); } catch (IOException ignore) {} if (input != null) try { input.close(); } catch (IOException ignore) {} } } 

Map this servlet in web.xml to url-pattern from /files/* so that you can get the excel file using http://example.com/contextname/files/filename.xls .

If it is actually an xlsx file, which by default is not recognized as the middle servletcontainer container (then ServletContext#getMimeType() will return application/octet-stream instead of the desired xlsx content type), then you need to add the following entry in web.xml :

 <mime-mapping> <extension>xlsx</extension> <mime-type>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</mime-type> </mime-mapping> 

For a more advanced example of a file servlet, you can find this article , which is also supported every time a download resumes.

+23
source

Source: https://habr.com/ru/post/1309746/


All Articles