一,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();
}