HttpServletResponse
什么是HttpSevletResponse
web服務器接收到客戶端的http請求,針對這個請求,分別創建一個代表請求的HttpServletRequest對象,代表響應的一個HttpServletResponse;
案例:下載文件
下載文件思路:
- 下載文件路徑
- 下載文件名稱
- 瀏覽器支持下載格式
- 獲取下載文件的輸入流
- 創建緩沖區
- 獲取OutputStream對象
- 將FileOutStream流寫入到buffer緩沖區
- OutputStream將緩沖區數據輸出到客戶端
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1. 下載文件路徑
String realPath = "xxxx";
System.out.println("下載文件的路徑:"+realPath);
// 2. 下載文件名稱
String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
// 3. 瀏覽器支持下載格式
resp.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(fileName,"UTF-8"));
// 4. 獲取下載文件的輸入流
FileInputStream in = new FileInputStream(realPath);
// 5. 創建緩沖區
int len = 0;
byte[] buffer = new byte[1024];
// 6. 獲取OutputStream對象
ServletOutputStream out = resp.getOutputStream();
// 7. 將FileOutputStream流寫入到buffer緩沖區,使用OutputStream將緩沖區中的數據輸出到客戶端!
while ((len=in.read(buffer))>0){
out.write(buffer,0,len);
}
in.close();
out.close();
}

浙公網安備 33010602011771號