improve download code

pull/1/head
Thomas Ballmann 4 years ago
parent c40ff1d8dc
commit 6a1c6f8bba

@ -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();

Loading…
Cancel
Save