1 | server.on("/upload", HTTP_GET, []() { // if the client requests the upload page
|
2 | handleFileUploadDialog();
|
3 | });
|
4 |
|
5 | server.on("/upload", HTTP_POST, // if the client posts to the upload page
|
6 | [](){ server.send(200); }, // Send status 200 (OK) to tell the client we are ready to receive
|
7 | handleFileUpload // Receive and save the file
|
8 | );
|
9 |
|
10 |
|
11 | void handleFileUploadDialog(){
|
12 | String page = FPSTR(HTTP_HEAD);
|
13 | page.replace("{v}", "File Upload");
|
14 | page += FPSTR(HTTP_STYLE);
|
15 | page += FPSTR(HTTP_JS_IMAGE);
|
16 | page += FPSTR(HTTP_HEAD_END);
|
17 | page += F("<h1>File Upload</h1><br />");
|
18 | page += F("<form action=\"/upload\" method=\"POST\" enctype=\"multipart/form-data\">");
|
19 | page += F("<input type=\"file\" name=\"data\">");
|
20 | page += F("<input type=\"submit\" value=\"Upload\">");
|
21 | page += F("</form>");
|
22 |
|
23 | page += FPSTR(HTTP_END);
|
24 |
|
25 | server.send(200, "text/html", page);
|
26 |
|
27 | }
|
28 |
|
29 | void handleFileUpload(){ // upload a new file to the SPIFFS
|
30 | HTTPUpload& upload = server.upload();
|
31 | if(upload.status == UPLOAD_FILE_START){
|
32 | String filename = upload.filename;
|
33 | if(!filename.startsWith("/")) filename = "/"+filename;
|
34 | Serial.print("handleFileUpload Name: "); Serial.println(filename);
|
35 | fsUploadFile = SPIFFS.open(filename, "w"); // Open the file for writing in SPIFFS (create if it doesn't exist)
|
36 | filename = String();
|
37 | } else if(upload.status == UPLOAD_FILE_WRITE){
|
38 | if(fsUploadFile)
|
39 | fsUploadFile.write(upload.buf, upload.currentSize); // Write the received bytes to the file
|
40 | } else if(upload.status == UPLOAD_FILE_END){
|
41 | if(fsUploadFile) { // If the file was successfully created
|
42 | fsUploadFile.close(); // Close the file again
|
43 | Serial.print("handleFileUpload Size: "); Serial.println(upload.totalSize);
|
44 | handleSuccess();
|
45 | } else {
|
46 | server.send(500, "text/plain", "500: couldn't create file");
|
47 | }
|
48 | }
|
49 | }
|