Example sketches for the new Arduino IDE for ESP8266

Moderator: igrr

User avatar
By mvdbro
#30054 I'm looking for a way to send binary data to the webclient (browser) to download to file.

This code snippet works to have some string data saved to file using your browser:

String reply = "this is a demo string";
WebServer.sendHeader("Content-Disposition", "attachment; filename=settings.txt");
WebServer.send(200, "application/octet-stream", reply);

and this snippet works for sending a file on SPIFFS:

dataType = F("application/octet-stream");
File dataFile = SPIFFS.open(path.c_str(), "r");
WebServer.sendHeader("Content-Disposition", "attachment;");
WebServer.streamFile(dataFile, dataType);

But I would like to send a byte array from memory to the webbrowser, so I guess that I would need something like:

WebServer.StreamData(byte* data, int datasize)

Is there a method of sending binary data without using StreamFile ?

I can convert the binary data to hex string beforehand, but this is not what I want because it doubles the filesize.

Does anyone have a sample code on how to achieve this?
User avatar
By mvdbro
#30063 Thanks, didn't realize you could still do it that way. This is working for me now, sending a 2kb data array:

WiFiClient client = WebServer.client();
client.print("HTTP/1.1 200 OK\r\n");
client.print("Content-Disposition: attachment; filename=config.txt\r\n");
client.print("Content-Type: application/octet-stream\r\n");
client.print("Content-Length: 2048\r\n");
client.print("Connection: close\r\n");
client.print("Access-Control-Allow-Origin: *\r\n");
client.print("\r\n");
client.write((const char*)data, 2048);

But it seems you have to do all detailed header stuff this way, can't mix it like this can you?:

WebServer.sendHeader("Content-Disposition", "attachment; filename=config.txt");
client.write((const char*)data, 2048);
WebServer.send(200, "application/octet-stream", "");
User avatar
By martinayotte
#30068
mvdbro wrote:But it seems you have to do all detailed header stuff this way, can't mix it like this can you?:

WebServer.sendHeader("Content-Disposition", "attachment; filename=config.txt");
client.write((const char*)data, 2048);
WebServer.send(200, "application/octet-stream", "");


There is maybe a way since there is a method setContentLength() that allows to set the length before the private function _prepareHeader() is doing its job.
Since I've not tried it, I don't know if it is working or if there are bugs.
But ultimately, it should work.