O'Reilly logo

Java Servlet & JSP Cookbook by Bruce W. Perry

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

13.2. Sending a Word Processing File

Problem

You want to send a Microsoft Word file as binary data.

Solution

Use the same servlet setup as described in Recipe 13.1, but include a different file extension and a Content-Type of application/msword.

Discussion

You might have some Microsoft Word documents that you want to distribute as binary data from a servlet. Example 13-2 uses the same basic structure as Example 13-1, with a few changes to adapt the servlet for sending Microsoft Word documents. These include accessing a different context-param element (you could keep all files for download in the same directory, however), and using a different MIME type as the parameter for the setContentType( ) method, as in response.setContentType("application/msword").

Example 13-2. Sending a Word file as binary data

package com.jspservletcookbook; import java.io.FileInputStream; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import javax.servlet.*; import javax.servlet.http.*; public class SendWord extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //get the filename from the "file" parameter String fileName = (String) request.getParameter("file"); if (fileName == null || fileName.equals("")) throw new ServletException( "Invalid or non-existent file parameter in SendWord."); // add the .doc suffix if it doesn't already exist if (fileName.indexOf(".doc") == -1) fileName = fileName ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required