Prosanto
Prosanto

Reputation: 924

File downloading - negative file length

I am trying to download a file (mp3) from my server.

I want to show the downloading progress, but I am facing a problem that whole time the file size is -1.

The screenshot: enter image description here
My code:

try {
    URL url = new URL(urls[0]);
    // URLConnection connection = url.openConnection();
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setDoOutput(true);
    connection.connect();
    int fileSize = connection.getContentLength();
    if (fileSize == -1)
        fileSize = connection.getHeaderFieldInt("Length", -1);
    InputStream is = new BufferedInputStream(url.openStream());
    OutputStream os = new FileOutputStream(myFile);

    byte data[] = new byte[1024];
    long total = 0;
    int count;
    while ((count = is.read(data)) != -1) {
        total += count;
        Log.d("fileSize", "Lenght of file: " + fileSize);
        Log.d("total", "Lenght of file: " + total);
        // publishProgress((int) (total * 100 / fileSize));
        publishProgress("" + (int) ((total * 100) / fileSize));
        os.write(data, 0, count);
    }
    os.flush();
    os.close();
    is.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

I get the garbage value for the fileSize which return -1 (int fileSize = connection.getContentLength();)

Upvotes: 6

Views: 1261

Answers (1)

kaqqao
kaqqao

Reputation: 15429

Inspect the headers the server is sending. Very probably the server is sending Transfer-Encoding: Chunked and no Content-Length header at all. This is a common practice in HTTP/1.1. If the server isn't sending the length, the client obviously can't know it. If this is the case, and you have no control over the server code, the best thing to do is probably display a spinner type of indicator only.

Upvotes: 2

Related Questions