From 6a1c6f8bbadbfac1092975fc4b95d607a113511f Mon Sep 17 00:00:00 2001 From: Thomas Ballmann Date: Wed, 11 Mar 2020 20:35:54 +0100 Subject: [PATCH] improve download code --- src/download.cpp | 59 ++++++++++-------------------------------------- 1 file changed, 12 insertions(+), 47 deletions(-) diff --git a/src/download.cpp b/src/download.cpp index 4fb46bf..a8fdcf9 100644 --- a/src/download.cpp +++ b/src/download.cpp @@ -9,13 +9,23 @@ bool downloadFile(String url, const char *path) // @note duration time: 200kb = 35sec write to flash Serial.println("Download file: " + url); + // tmp file bool hasError = false; String tmpFile = path; tmpFile += ".tmp"; + // track duration + long startMills = millis(); + + File file = SPIFFS.open(tmpFile, FILE_WRITE); + if (!file) + { + Serial.println("Failed to open file for writing"); + return false; + } + http.useHTTP10(true); // http1.1 chunked übertragung funktioniert irgendwie nicht http.setTimeout(7000); - http.begin(url); int httpCode = http.GET(); if (httpCode != HTTP_CODE_OK) @@ -25,53 +35,8 @@ bool downloadFile(String url, const char *path) } else { - // track duration - long startMills = millis(); - - // get lenght of document (is -1 when Server sends no Content-Length header) - int len = http.getSize(); - - // create buffer for read - uint8_t buff[1024] = {0}; - - // get tcp stream - WiFiClient *stream = http.getStreamPtr(); - - // persist image - File file = SPIFFS.open(tmpFile, FILE_WRITE); - if (!file) - { - Serial.println("Failed to open file for writing"); - hasError = true; - } - - // read all data from server - while (http.connected() && (len > 0 || len == -1)) - { - // get available data size - size_t size = stream->available(); - - if (size) - { - // read up to xxx byte - int c = stream->readBytes(buff, ((size > sizeof(buff)) ? sizeof(buff) : size)); - - // write to storage - if (file) - { - file.write(buff, c); - } - - if (len > 0) - { - len -= c; - } - } - - delay(1); - } + http.writeToStream(&file); - // done if (file) { file.close();