1.响应头设置字节。
使用response获得字节输出流
ServletOutputStream out = response.getOutputStream();
ServletOutputStream out = response.getOutputStream();
获取文件的绝对路径
String realPath = this.getServletContext().getRealPath("a.jpg");
String realPath = this.getServletContext().getRealPath("a.jpg");
获得服务器上的图片
FileInputStream in=new FileInputStream(realPath);
FileInputStream in=new FileInputStream(realPath);
package com.hdh.content;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ByteServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 用response获得字节输出流
ServletOutputStream sos = response.getOutputStream();
// 获取文件的绝对路径
String realPath = this.getServletContext().getRealPath("a.jpg");
// 获得服务器上的图片
FileInputStream fis = new FileInputStream(realPath);
int len = 0;
byte[] buffer = new byte[1024];
while ((len = fis.read(buffer)) > 0) {
sos.write(buffer, 0, len);
}
fis.close();
sos.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}