如何下载它之前知道一个文件的大小?如何下载、大小、文件

2023-09-12 21:40:57 作者:是你的胖虎吗

我要下载一个文件,我使用这code ,这基本上是一个 AsyncTask的,是为了更新进度条。但是,因为我不知道什么是文件的大小我一直有使用微调进度条。所以,我怎样才能得到文件的大小之前开始下载它,这样我就可以使用正常的进度条?

I have to download a file and I'm using this code, which is basically an AsyncTask that is meant to update a progress bar. But, since I don't know what's the file size I've been having to use the spinner progress bar. So, how can I get the file size before start downloading it so that I can use a normal progress bar?

推荐答案

你可以得到一个名为内容长度形成你的HTTP Response对象头,这将给你的文件的长度。 你应该注意到,虽然,有些服务器不返回的信息,并了解实际大小的唯一方法是阅读一切从响应。

you can get a header called Content-Length form the HTTP Response object that you get, this will give you the length of the file. you should note though, that some servers don't return that information, and the only way to know the actual size is to read everything from the response.

示例:

URL url = new URL("http://server.com/file.mp3");
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
int file_size = urlConnection.getContentLength();