<%@ page info="Random Image Show"
pageEncoding="UTF-8" contentType="image/jpg"
autoFlush="true" buffer="16kb" session="false" import="java.io.FileInputStream"
%><%
String[] imgpaths = {
"D:/images/testimg1.jpg",
"D:/images/testimg2.jpg",
"D:/images/testimg3.jpg"
};
ServletOutputStream sos = response.getOutputStream();
FileInputStream fis = new FileInputStream(imgpaths[(int) (Math.random() * imgpaths.length)]);
byte[] buf = new byte[100]; //缓冲区大小
int len = 0;
while ((len = fis.read(buf)) != -1) {
sos.write(buf, 0, len);
}
sos.flush();
sos.close();
fis.close();
%>
注意:在与out混用时会出错,因此在用完getOutputStream之后要使
out.clear();
out = pageContext.pushBody();
下面一个例子
文件代码如下:
OutputStream o=response.getOutputStream();
//输出文件用的字节数组,每次发送500个字节到输出流
byte b[]=new byte[500];
//下载的文件
File fileLoad=new File("f:/2000","book.zip");
//客户使用的保存文件的对话框
response.setHeader("Content-disposition","attachment;filename="+"book.zip");
//通知客户文件的MOME类型
response.setContentType("application/x-tar");
//通知客户文件的长度
long fileLength=fileLoad.length();
String length=String.valueOf(fileLength);
response.setHeader("Content_Length",length);
out.clear();
out = pageContext.pushBody();
//读取文件book.zip,并发送给客户下载
FileInputStream in=new FileInputStream(fileLoad);
int n=0;
while((n=in.read(b))!=-1)
{
o.write(b,0,n);
}