一個難題,servlet高手請進!
我在做一個jsp頁面的時候,點擊鏈接打開文檔,用了一個servlet處理,
比如 The test fiel( /Openfile?filename=data/test.xls)
-----------------------------------------------
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
HttpSession session = request.getSession();
String filename = request.getParameter( "file_name ");
filename = Globals.RTC_UP_PATH + "/ " + filename;
response.setHeader( "Content-disposition ",
"attachment;filename= " +
filename.replace( '\\ ', '/ ').
substring(filename.lastIndexOf( "/ ")));
String ext=filename.substring(filename.lastIndexOf( ". ")+1);
if(ext.equalsIgnoreCase( "xls ")){
System.out.println( "xlsfile: "+filename);
response.setContentType( "application/vnd.ms-excel ");
}
else{
System.out.println( "html: "+filename);
response.setContentType( "text/html ");
}
File doc = new File(filename);
ServletOutputStream out = response.getOutputStream();
FileInputStream fin = new FileInputStream(doc);
int b;
while ( (b = fin.read()) != -1) {
out.write(b);
}
System.out.println( "File is open ! ");
}
------------------
請問,這個doGet()方法如何寫,才可以實現我點擊候,IE自動調用excel,word,pdf打開這三種文件呢?我已經可以打開xls了,可是打開word,html出現亂碼,打開pdf的時候需要先下載到本地,然後才能打開......
[解决办法]
pdf response.setContentType( "application/pdf ");
word response.setContentType( "application/msword ");
html response.setContentType( "text/html;charset=gbk ");设置charset,文件的字符编码
[解决办法]
private void downLoad(String filePath,HttpServletResponse response,boolean isOnLine)
throws Exception{
File f = new File(filePath);
if(!f.exists()){
response.sendError(404, "File not found! ");
return;
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] buf = new byte[1024];
int len = 0;
response.reset(); //非常重要
if(isOnLine){ //在线打开方式
URL u = new URL( "file:/// "+filePath);
response.setContentType(u.openConnection().getContentType());
response.setHeader( "Content-Disposition ", "inline; filename= "+URLEncoder.encode(f.getName(), "UTF-8 ") );
//文件名应该编码成UTF-8
}
else{ //纯下载方式
response.setContentType( "application/x-msdownload ");
response.setHeader( "Content-Disposition ", "attachment; filename= " + URLEncoder.encode(f.getName(), "UTF-8 "));
}
OutputStream out = response.getOutputStream();
while((len = br.read(buf)) > 0)
out.write(buf,0,len);
br.close();
out.close();
}