Read and save part of file stream via IdHTTP

限于喜欢 提交于 2019-12-05 22:33:40

If the HTTP server supports byte ranges for the desired URL (via the Range request header), you can request just the specific bytes you want, and that is all the server will send. You can use the TIdHTTP.Request.Range property for that when calling TIdHTTP.Get(). To discover if the server supports byte ranges, use TIdHTTP.Head() first to get the URL's headers, and then check if there is an Accept-Ranges: bytes header present (see the TIdHTTP.Response.AcceptRanges property).

If the server does not support byte ranges, you will have to continue using the code you currently have, just make some changes to it:

  • Instead of calling fs.SaveToFile(), create a separate TFileStream object and pass the TMemoryStream to its CopyFrom() method, that way you can specify exactly how many bytes to save.

  • Use the TIdHTTP.OnWork event, or use a TIdEventStream, or derive a custom TStream that overrides Write(), in order to keep track of how many bytes are being downloaded, so you can abort the download (by raising an exception, like EAbort via SysUtils.Abort()) once the desired number of bytes have been received.

Of course, either approach is byte oriented not line oriented. If you need to be line-oriented, and particularly if the lines are variable length, then you will have to use the second approach above, using TIdEventStream or a custom TStream, so you can implement line parsing logic and save only complete lines to your file, and then abort once you have received the desired number of lines.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!