在 Play 框架 scala 中限制下载速率的最佳方法
问题:限制二进制文件下载速率。
def test = {
Logger.info("Call test action")
val file = new File("/home/vidok/1.jpg")
val fileIn = new FileInputStream(file)
response.setHeader("Content-type", "application/force-download")
response.setHeader("Content-Disposition", "attachment; filename=\"1.jpg\"")
response.setHeader("Content-Length", file.lenght + "")
val bufferSize = 1024 * 1024
val bb = new Array[Byte](bufferSize)
val bis = new java.io.BufferedInputStream(is)
var bytesRead = bis.read(bb, 0, bufferSize)
while (bytesRead > 0) {
bytesRead = bis.read(bb, 0, bufferSize)
//sleep(1000)?
response.writeChunk(bytesRead)
}
}
但它仅适用于文本文件。如何使用二进制文件?
Problem: limit binary files download rate.
def test = {
Logger.info("Call test action")
val file = new File("/home/vidok/1.jpg")
val fileIn = new FileInputStream(file)
response.setHeader("Content-type", "application/force-download")
response.setHeader("Content-Disposition", "attachment; filename=\"1.jpg\"")
response.setHeader("Content-Length", file.lenght + "")
val bufferSize = 1024 * 1024
val bb = new Array[Byte](bufferSize)
val bis = new java.io.BufferedInputStream(is)
var bytesRead = bis.read(bb, 0, bufferSize)
while (bytesRead > 0) {
bytesRead = bis.read(bb, 0, bufferSize)
//sleep(1000)?
response.writeChunk(bytesRead)
}
}
But its working only for the text files. How to work with binary files?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的基本想法是正确的:每次读取一定数量的字节(存储在缓冲区中)时,您需要:
sleep(Y)
这已经是一个很好的问题了关于这个就在这里,应该有您需要的一切。我认为尤其是 ThrottledInputStream 解决方案(这不是公认的答案)相当优雅。
需要记住的几点:
Content-Range
)和 Java NIO。但是,请记住,这将使事情变得更加复杂。You've got the basic idea right: each time you've read a certain number of bytes (which are stored in your buffer) you need to:
sleep(Y)
on the downloading thread if needed to slow the download rate downThere's already a great question about this right here that should have everything you need. I think especially the
ThrottledInputStream
solution (which is not the accepted answer) is rather elegant.A couple of points to keep in mind:
Content-Range
) and Java NIO. However, keep in mind that this will make thing a lot more complex.我不会实现任何好的网络服务器应该能够为我实现的东西。在企业系统中,这种事情通常由 Web 入口服务器或防火墙处理。但如果你必须这样做,那么 tmbrggmn 的答案对我来说看起来不错。 NIO 是一个很好的建议。
I wouldn't implement something which any good webserver should be able to for me. In enterprise systems this kind of thing is normally handled by a web entry server or firewall. But if you have to do this, then the answer by tmbrggmn looks good to me. NIO is a good tip.