java以流的形式显示文件
/**
* 在客户端打开附件
*/
public void doGet(HttpServletRequest req, HttpServletResponse rep) throws ServletException,IOException{
HttpServletRequest request=(HttpServletRequest)req;
javax.servlet.http.HttpServletResponse response=(HttpServletResponse)rep;
ServletOutputStream outw=response.getOutputStream();
try{
String fileId=request.getParameter("fileId");
attachment att=attachmentManager.getAttachment(fileId);
response.setContentType(att.getMimeType());
String title=att.getTitle();
if(title.endsWith(".gw")){
title = title.substring(0, title.lastIndexOf(".")) + ".gd";
}
response.setHeader("Content-Disposition","attachment;filename=\"" +new String(title.getBytes(),"iso-8859-1") + "\"");
String filePath=att.getFilePath();
if(filePath.endsWith(".gw")){
filePath=filePath.substring(0,filePath.lastIndexOf("."))+".gd";
}
FileInputStream inp = new FileInputStream(getUploadPath() + filePath);
int i;
byte [] buffer = new byte[1024];
while ( (i = inp.read(buffer)) != -1) {
outw.write(buffer, 0, i);
}
inp.close();
outw.flush();
}
catch (Exception e){
e.printStackTrace();
} finally {
outw.close();
}
}
50校招生网 http://www.50xiao.com
/**
* 在客户端打开附件
*/
public void doGet(HttpServletRequest req, HttpServletResponse rep) throws ServletException,IOException{
HttpServletRequest request=(HttpServletRequest)req;
javax.servlet.http.HttpServletResponse response=(HttpServletResponse)rep;
ServletOutputStream outw=response.getOutputStream();
try{
String fileId=request.getParameter("fileId");
attachment att=attachmentManager.getAttachment(fileId);
response.setContentType(att.getMimeType());
String title=att.getTitle();
if(title.endsWith(".gw")){
title = title.substring(0, title.lastIndexOf(".")) + ".gd";
}
response.setHeader("Content-Disposition","attachment;filename=\"" +new String(title.getBytes(),"iso-8859-1") + "\"");
String filePath=att.getFilePath();
if(filePath.endsWith(".gw")){
filePath=filePath.substring(0,filePath.lastIndexOf("."))+".gd";
}
FileInputStream inp = new FileInputStream(getUploadPath() + filePath);
int i;
byte [] buffer = new byte[1024];
while ( (i = inp.read(buffer)) != -1) {
outw.write(buffer, 0, i);
}
inp.close();
outw.flush();
}
catch (Exception e){
e.printStackTrace();
} finally {
outw.close();
}
}
50校招生网 http://www.50xiao.com
本文介绍了一种使用Java实现的通过HTTP响应将文件以流的形式返回给客户端的方法,该方法适用于下载附件等场景。文中详细展示了如何设置HTTP响应头、读取文件并将其发送到客户端的过程。
1396

被折叠的 条评论
为什么被折叠?



