File upload - negative file length

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

I want to show the download process, but you are facing a problem that the file size is -1 all the time.

Screenshot: enter image description here

My code is:

 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 fileSize that return -1 ( int fileSize = connection.getContentLength(); )

+6
source share
1 answer

Check the headers sent by the server. The server probably sends the Transfer-Encoding: Chunked and no Content-Length header altogether. This is a common practice in HTTP / 1.1. If the server does not send the length, the client obviously cannot know this. If this is the case, and you have no control over the server code, it is best to probably only display a spinner indicator.

+2
source

Source: https://habr.com/ru/post/986873/


All Articles