[ Team LiB ] Previous Section Next Section

Recipe 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 + ".doc";
          
      //where are Word files kept?
     String wordDir = getServletContext( ).getInitParameter("word-dir");
     if (wordDir == null || wordDir.equals(""))
           throw new ServletException(
             "Invalid or non-existent wordDir context-param.");
          
     ServletOutputStream stream = null;
     BufferedInputStream buf = null;
     try{
     
     stream = response.getOutputStream( );
     File doc = new File(wordDir + "/" + fileName);
     
     //set response headers
     response.setContentType("application/msword");
      
     response.addHeader(
        "Content-Disposition","attachment; filename="+fileName );

     response.setContentLength( (int) doc.length( ) );
      
     FileInputStream input = new FileInputStream(doc);
     buf = new BufferedInputStream(input);
     int readBytes = 0;

     //read from the file; write to the ServletOutputStream
     while((readBytes = buf.read( )) != -1)
        stream.write(readBytes);

     } catch (IOException ioe){
     
        throw new ServletException(ioe.getMessage( ));
         
     } finally {
     
      //close the input/output streams
     if(stream != null)
         stream.close( );
      if(buf != null)
          buf.close( );
     }
    
 } //end doGet
   
 public void doPost(HttpServletRequest request, 
    HttpServletResponse response) throws ServletException, 
      IOException {
        
      doGet(request,response);
 } 
}

The ServletOutputStream (the information sent as the servlet response) and the BufferedInputStream (from which the servlet gets the file to send) are both closed in the finally block to make sure any system resources they use are released. See the end of the discussion in Recipe 13.1 for a further description of this code, including the warning at the end of that recipe about the Internet Explorer-related exception.

See Also

Recipe 13.1 on sending a PDF file; Recipe 13.3 and Recipe 13.4 on sending XML and MP3 files as binary data; Recipe 13.5 on getting an input stream representing a web resource such as web.xml; RFC technical documents on MIME: ftp://ftp.rfc-editor.org/in-notes/rfc2045.txt and ftp://ftp.rfc-editor.org/in-notes/rfc2046.txt; RFC 2183 at ftp://ftp.rfc-editor.org/in-notes/rfc2183.txt for background information on the Content-Disposition header; the Media Types section of the HTTP Pocket Reference by Clinton Wong (O'Reilly); Chapter 1 introducing the development of a servlet.

    [ Team LiB ] Previous Section Next Section