package zdh.cm.response;
/*
* 以下载方式打开资源
* 下载资源
*
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ResponseDemo5 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//选择要被下载的资源URI
File file = new File("c:/work.txt");
//告诉浏览器以下载的方法打开
response.setHeader("Content-Disposition", "attachment; filename="+file.getName());
//创建字节输入流以读取本地文件
FileInputStream in = new FileInputStream(file);
//创建字节输出流,将文件数据写出给浏览器
OutputStream out = response.getOutputStream();
byte [] buf = new byte[1024];
int len = 0;
//边读边写
while((len = in.read(buf))!=-1){
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
http协议之response案例四:以下载方式打开资源/下载文件
最新推荐文章于 2024-03-22 08:17:54 发布