Dear comunity please tell me what is wrong with it code.
I am using esp8266 mcu. HTTP request ends ok, but how can i save the file.
Method "writeToStream" of HTTPClient class work good with 'Serial' stream but returns negative (as we know it is error) while writes to file stream.
void loop() {
File file;
// wait for WiFi connection
if ((WiFiMulti.run() == WL_CONNECTED)) {
WiFiClient client;
HTTPClient http;
Serial.print("[HTTP] begin...\n");
file = LittleFS.open("/bin.bin", "w+");
if (http.begin(client, "http://mcu-bin-upd.000webhostapp.com/example.bin")) { // HTTP
http.collectHeaders(headerKeys,numberOfHeaders);
Serial.print("[HTTP] GET...\n");
// start connection and send HTTP header
int httpCode = http.GET();
// httpCode will be negative on error
if (httpCode > 0) {
// HTTP header has been send and Server response header has been handled
Serial.printf("[HTTP] GET... code: %d\n", httpCode);
// file found at server
if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
Serial.printf("My header 2/%d\n", http.headers());
if(http.hasHeader("Content-type")){
Serial.printf("Content-type: %s \n", http.header("Content-type").c_str());
}
if(http.hasHeader("Content-length")){
int bytesWritten;
int contLen = http.header("Content-length").toInt();
Serial.printf("Content-length: %d \n", contLen);
if(file){
bytesWritten = http.writeToStream(&Serial);
Serial.print("\n");
Serial.printf("Stream.Serial written bytes: %d\n", bytesWritten);
bytesWritten = http.writeToStream(&file);
Serial.printf("Stream.file written bytes: %d\n", bytesWritten);
} else {
Serial.print("The file not opened. \n");
}
}
}
file.close();
} else {
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
} else {
Serial.printf("[HTTP} Unable to connect\n");
}//if (http.begin...
file.close();
}
delay(20000);
}
Mount LittleFS
Listing directory: /
FILE: bin.bin SIZE: 0 CREATION: 1970-01-01 00:00:07
LAST WRITE: 1970-01-01 00:00:00
[SETUP] WAIT ...
[HTTP] begin...
[HTTP] GET...
[HTTP] GET... code: 200
My header 2/2
Content-type: application/octet-stream
Content-length: 20
(edited by me. below is my file content. it's ok)
яяяя[00][00][00][00][01][02][03][04][05][06][07][08][05][05][05][05]
Stream.Serial written bytes: 20
Stream.file written bytes: -10