How to download large image file (~2mb) from web server to SD card?

Hi,

I need to download files (image files: bmp, jpg etc) that are larger than the RAM and save it to an SD card. How can I do this? I can download small text files, but I’m not sure how to download larger files. Here is the code I’m using:

int downloadDisplayImage(){
int err = http.get(downloadUrl);
int statusCode = http.responseStatusCode();
int bodyLength = http.contentLength();
char filename = “img1.bmp”;
char c;
int retries = 0;
const int retryLimit = 5;
int totalBytesRead = 0;
// Check to see if the file exists:
if (SD.exists(filename)) {
DEBUG_PRINTLN(“Destinamion file exists.”);
// delete the file:
DEBUG_PRINTLN(“Removing destinamion file…”);
SD.remove(filename);
delay(2);
}
File destFile = SD.open(filename, FILE_WRITE);
if(err != 0){
DEBUG_PRINTLN(“HTTP request cannot be started”);
DEBUG_PRINT("Error code: ");
DEBUG_PRINTLN(err);
return 1;
}
DEBUG_PRINTLN(“HTTP request started OK”);
if(statusCode < 0){
DEBUG_PRINTLN(“Failed to get status code”);
return 1;
}
DEBUG_PRINT("HTTP status code: ");
DEBUG_PRINTLN(statusCode);
DEBUG_PRINT("Content length: ");
DEBUG_PRINTLN(bodyLength);
DEBUG_PRINTLN();
DEBUG_PRINT(“Start downloading…”);
unsigned long timeoutStart = millis();
int i = 0;
while(1){
uint8_t buff[BUFF_SIZE];
i = i + 1;
if(http.endOfBodyReached()){
DEBUG_PRINTLN(“Reached end of body”);
break;
}
int bytesToRead = http.available();
if(bytesToRead > BUFF_SIZE){
bytesToRead = BUFF_SIZE;
}
if(!http.available()){
delay(networkDelay);
continue;
}
if((millis() - timeoutStart) > networkTimeout){
if(totalBytesRead < bodyLength){
DEBUG_PRINTLN(“Waiting for server”);
delay(2);
retries = retries + 1;
if(retries > retryLimit){
DEBUG_PRINTLN(“Too many retries”);
break;
}
continue;
}
break;
}
http.read(buff, bytesToRead);
totalBytesRead = totalBytesRead + bytesToRead;
destFile.write(buff, bytesToRead);
}
DEBUG_PRINT("Number of HTTP read cycle: ");
DEBUG_PRINTLN(i);
DEBUG_PRINT("Total bytes read: ");
DEBUG_PRINTLN(totalBytesRead);
destFile.close();
return totalBytesRead;
}

Here is an example image url: http:customsoftware.com.sg/display_image/uploads/display_image.bmp