How to open a ".doc" file with ms word directly with this servlet?
843840Aug 1 2002 — edited Jan 19 2004Here is a servlet for opening a word or a excel or a powerpoint or a pdf file,but I don't want the "file download" dialog appear,eg:when i using this servlet to open a word file,i want open the ".doc" file with ms word directly,not in IE or save.
*********************************************************************************
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class OpenWord extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException {
String strFileName = req.getParameter("filename");
int len = 0;
String strFileType1 = "application/msword";
String strFileType2 = "application/vnd.ms-excel";
String strFileType3 = "application/vnd.ms-powerpoint";
String strFileType4 = "application/pdf";
String strFileType = "";
if(strFileName != null) {
len = strFileName.length();
if(strFileName.substring(len-3,len).equalsIgnoreCase("doc")) {
strFileType = strFileType1;
} else if(strFileName.substring(len-3,len).equalsIgnoreCase("xls")) {
strFileType = strFileType2;
} else if(strFileName.substring(len-3,len).equalsIgnoreCase("ppt")) {
strFileType = strFileType3;
} else if(strFileName.substring(len-3,len).equalsIgnoreCase("pdf")) {
strFileType = strFileType4;
} else {
strFileType = strFileType1;
}
}
if(strFileName != null) {
ServletOutputStream out = res.getOutputStream();
res.setContentType(strFileType); // MIME type for word doc
//if uncomment below sentence,the "file download" dialog will appear twice.
//res.setHeader("Content-disposition","attachment;filename="+strFileName);
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
String path = "d:\\"; //put a word or a excel file here,eg a.doc
try {
File f = new File(path.concat(strFileName));
FileInputStream fis = new FileInputStream(f);
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(out);
byte[] buff = new byte[2048];
int bytesRead;
while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch(NullPointerException e) {
System.out.println ( "NullPointerException." );
throw e;
} catch(FileNotFoundException e) {
System.out.println ( "FileNotFoundException." );
throw e;
} catch(final IOException e) {
System.out.println ( "IOException." );
throw e;
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
}
}
}