@WebServlet(urlPatterns = "/copyFile")
public class CopyFile extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
*
* response响应数据,也可以使用字节输出流getOutPutStream() 得到字节输出流对象来写数据
*
*
* 文件复制:一读(本地)一写(客户端)
* 读写本地文件(硬盘上)必须使用自己创建的流对象(本地流)
* 写回给客户端,两者之间进行交互,必须使用网络流,即服务器提供的response和request对象中提供的流对象
*
*
*
* */
//获取本地文件的绝对路径
String path = getServletContext().getRealPath("1.jpg");
//获取本地流的字节输入流对象
FileInputStream fs = new FileInputStream(new File(path));
//获取网络字节输出流对象
ServletOutputStream os = response.getOutputStream();
//读文件,写文件
byte[] bytes = new byte[1024];
int len=0;
while ((len=fs.read(bytes))!=-1){
os.write(bytes,0,len);
}
fs.close();
}
}
Response之文件复制案例(从servlet写回给客户端:本地流+网络流)
最新推荐文章于 2023-06-29 15:20:24 发布