Ich versuche, eine Datei (mp3) von meinem Server herunterzuladen.Datei herunterladen - negative Dateilänge
Ich möchte den Download-Fortschritt zeigen, aber ich habe ein Problem, dass die gesamte Dateigröße -1
ist.
Der Screenshot:
Mein 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();
}
ich den Müll Wert für die fileSize
erhalten, die -1
(int fileSize = connection.getContentLength();
) zurückkehren
Verwenden Sie ein Befehlszeilentool wie ** 'curl' **, um die Header zu prüfen, die vom Server zurückkommen, wenn Sie diese URL manuell herunterladen. Vielleicht legt der Server keine längenbezogenen Header fest. – CommonsWare
Manchmal ist die Länge unbekannt - es hängt von der Serverseite ab. Nichts ist falsch mit Ihrer Lösung – Toumash
@Prosanto Wie ich sehe, auch wenn es nicht richtig angezeigt wird sollte es herunterladen. Funktioniert die heruntergeladene Datei? – Chaoz