作者:Not-Only-For曾广超 | 来源:互联网 | 2023-09-24 12:26
123456789101112131415161718192021222324252627282930313233public class DownloadServlet extends HttpSe
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| public class DownloadServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//通过get方式取得文件名
String filename = request.getParameter("filename");//movie.mp4
response.setContentType(this.getServletContext().getMimeType(filename));
response.setHeader("Content-Disposition", "attachment;filename="+filename);
String path = this.getServletContext().getRealPath("download/"+filename);
InputStream in = new FileInputStream(path);
ServletOutputStream out = response.getOutputStream();
//实现IO
int len = 0;
byte[] buffer = new byte[1024];
while((len=in.read(buffer))>0){
out.write(buffer, 0, len);
}
in.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
} |
java的socket.io我有点不明白,比如上面代码我下载一个movie.mp4,它有100M文件确实不小,这里的ServletOutputStream是一次性写完100M的文件再传给客户端,还是写一次1024字节的字节数组或者是写满response缓冲区一次传一次客户端,但是如果是后者的话怎么保证读服务器端的写入速度小于客户端的读取速度?(node的流就会出现这种情况也就是文件下载不全!)是使用synchronized同步锁来解决么?
我看一个视频讲它讲的是doGet函数执行完了,才会把response传给tomcat内核封装成httpResponse对象(响应行头体)传给客户端,这意思明显是一次性写完100M再传客户端,这太耗费内存了,感觉那个视频说的不对!