关键词:
ESP8266 or ESP32开启WebServe服务实现文件上传和下载功能测试实例代码
- 本实例需要外接TF卡模块
Micro SD卡和MIni SD卡版本参数
- 需要的库
#ifdef ESP8266
#include <ESP8266WiFi.h> // Built-in
#include <ESP8266WiFiMulti.h> // Built-in
#include <ESP8266WebServer.h> // Built-in
#include <ESP8266mDNS.h>
#else
#include <WiFi.h> // Built-in
#include <WiFiMulti.h> // Built-in
#include <ESP32WebServer.h> // https://github.com/Pedroalbuquerque/ESP32WebServer download and place in your Libraries folder
#include <ESPmDNS.h>
#include "FS.h"
#endif
- 实例代码
/*
*
* ESP32/ESP8266 example of downloading and uploading a file from or to the ESP device's Filing System
* WiFi信息和静态IP地址信息放在Network.h中
*/
#ifdef ESP8266
#include <ESP8266WiFi.h> // Built-in
#include <ESP8266WiFiMulti.h> // Built-in
#include <ESP8266WebServer.h> // Built-in
#include <ESP8266mDNS.h>
#else
#include <WiFi.h> // Built-in
#include <WiFiMulti.h> // Built-in
#include <ESP32WebServer.h> // https://github.com/Pedroalbuquerque/ESP32WebServer download and place in your Libraries folder
#include <ESPmDNS.h>
#include "FS.h"
#endif
#include "Network.h"
#include "Sys_Variables.h"
#include "CSS.h"
#include <SD.h>
#include <SPI.h>
#ifdef ESP8266
ESP8266WiFiMulti wifiMulti;
ESP8266WebServer server(80);
#else
WiFiMulti wifiMulti;
ESP32WebServer server(80);
#endif
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void setup(void)
Serial.begin(115200);
if (!WiFi.config(local_IP, gateway, subnet, dns)) //WiFi.config(ip, gateway, subnet, dns1, dns2);
Serial.println("WiFi STATION Failed to configure Correctly");
wifiMulti.addAP(ssid_1, password_1); // 将需要连接的一系列WiFi ID和密码Network.h中
wifiMulti.addAP(ssid_2,password_2); // ESP8266-NodeMCU再启动后会扫描当前网络
wifiMulti.addAP(ssid_3, password_3); // 环境查找是否有这里列出的WiFi ID。如果有
//wifiMulti.addAP(ssid_4, password_4); //
Serial.println("Connecting ...");
while (wifiMulti.run() != WL_CONNECTED) // Wait for the Wi-Fi to connect: scan for Wi-Fi networks, and connect to the strongest of the networks above
delay(250); Serial.print('.');
Serial.println("\\nConnected to "+WiFi.SSID()+" Use IP address: "+WiFi.localIP().toString()); // Report which SSID and IP is in use
// The logical name http://fileserver.local will also access the device if you have 'Bonjour' running or your system supports multicast dns
if (!MDNS.begin(servername)) // Set your preferred server name, if you use "myserver" the address would be http://myserver.local/
Serial.println(F("Error setting up MDNS responder!"));
ESP.restart();
#ifdef ESP32
// Note: SD_Card readers on the ESP32 will NOT work unless there is a pull-up on MISO, either do this or wire one on (1K to 4K7)
Serial.println(MISO);
pinMode(2,INPUT_PULLUP);
#endif
Serial.print(F("Initializing SD card..."));
if (!SD.begin(SD_CS_pin)) // see if the card is present and can be initialised. Wemos SD-Card CS uses D8
Serial.println(F("Card failed or not present, no SD Card data logging possible..."));
SD_present = false;
else
Serial.println(F("Card initialised... file access enabled..."));
SD_present = true;
// Note: Using the ESP32 and SD_Card readers requires a 1K to 4K7 pull-up to 3v3 on the MISO line, otherwise they do-not function.
//----------------------------------------------------------------------
/ Server Commands
server.on("/", HomePage);
server.on("/download", File_Download);
server.on("/upload", File_Upload);
server.on("/fupload", HTTP_POST,[]() server.send(200);, handleFileUpload);
/ End of Request commands
server.begin();
Serial.println("HTTP server started");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void loop(void)
server.handleClient(); // Listen for client connections
// All supporting functions from here...
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void HomePage()
SendHTML_Header();
webpage += F("<a href='/download'><button>Download</button></a>");
webpage += F("<a href='/upload'><button>Upload</button></a>");
append_page_footer();
SendHTML_Content();
SendHTML_Stop(); // Stop is needed because no content length was sent
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void File_Download() // This gets called twice, the first pass selects the input, the second pass then processes the command line arguments
if (server.args() > 0 ) // Arguments were received
if (server.hasArg("download")) SD_file_download(server.arg(0));
else SelectInput("Enter filename to download","download","download");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void SD_file_download(String filename)
if (SD_present)
File download = SD.open("/"+filename);
if (download)
server.sendHeader("Content-Type", "text/text");
server.sendHeader("Content-Disposition", "attachment; filename="+filename);
server.sendHeader("Connection", "close");
server.streamFile(download, "application/octet-stream");
download.close();
else ReportFileNotPresent("download");
else ReportSDNotPresent();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void File_Upload()
append_page_header();
webpage += F("<h3>Select File to Upload</h3>");
webpage += F("<FORM action='/fupload' method='post' enctype='multipart/form-data'>");
webpage += F("<input class='buttons' style='width:40%' type='file' name='fupload' id = 'fupload' value=''><br>");
webpage += F("<br><button class='buttons' style='width:10%' type='submit'>Upload File</button><br>");
webpage += F("<a href='/'>[Back]</a><br><br>");
append_page_footer();
server.send(200, "text/html",webpage);
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
File UploadFile;
void handleFileUpload() // upload a new file to the Filing system
HTTPUpload& uploadfile = server.upload(); // See https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266WebServer/srcv
// For further information on 'status' structure, there are other reasons such as a failed transfer that could be used
if(uploadfile.status == UPLOAD_FILE_START)
String filename = uploadfile.filename;
if(!filename.startsWith("/")) filename = "/"+filename;
Serial.print("Upload File Name: "); Serial.println(filename);
SD.remove(filename); // Remove a previous version, otherwise data is appended the file again
UploadFile = SD.open(filename, FILE_WRITE); // Open the file for writing in SPIFFS (create it, if doesn't exist)
filename = String();
else if (uploadfile.status == UPLOAD_FILE_WRITE)
if(UploadFile) UploadFile.write(uploadfile.buf, uploadfile.currentSize); // Write the received bytes to the file
else if (uploadfile.status == UPLOAD_FILE_END)
if(UploadFile) // If the file was successfully created
UploadFile.close(); // Close the file again
Serial.print("Upload Size: "); Serial.println(uploadfile.totalSize);
webpage = "";
append_page_header();
webpage += F("<h3>File was successfully uploaded</h3>");
webpage += F("<h2>Uploaded File Name: "); webpage += uploadfile.filename+"</h2>";
webpage += F("<h2>File Size: "); webpage += file_size(uploadfile.totalSize) + "</h2><br>";
append_page_footer();
server.send(200,"text/html",webpage);
else
ReportCouldNotCreateFile("upload");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void SendHTML_Header()
server.sendHeader("Cache-Control", "no-cache, no-store, must-revalidate");
server.sendHeader("Pragma", "no-cache");
server.sendHeader("Expires", "-1");
server.setContentLength(CONTENT_LENGTH_UNKNOWN);
server.send(200, "text/html", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves.
append_page_header();
server.sendContent(webpage);
webpage = "";
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void SendHTML_Content()
server.sendContent(webpage);
webpage = "";
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void SendHTML_Stop()
server.sendContent("");
server.client().stop(); // Stop is needed because no content length was sent
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void SelectInput(String heading1, String command, String arg_calling_name)
SendHTML_Header();
webpage += F("<h3>"); webpage += heading1 + "</h3>";
webpage += F("<FORM action='/"); webpage += command + "' method='post'>"; // Must match the calling argument e.g. '/chart' calls '/chart' after selection but with arguments!
webpage += F("<input type='text' name='"); webpage += arg_calling_name; webpage += F("' value=''><br>");
webpage += F("<type='submit' name='"); webpage += arg_calling_name; webpage += F("' value=''><br>");
webpage += F("<a href='/'>[Back]</a>");
append_page_footer();
SendHTML_Content();
SendHTML_Stop();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void ReportSDNotPresent()
SendHTML_Header();
webpage += F("<h3>No SD Card present</h3>");
webpage += F("<a href='/'>[Back]</a><br><br>");
append_page_footer();
SendHTML_Content();
SendHTML_Stop();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void ReportFileNotPresent(String target)
SendHTML_Header();
webpage += F("<h3>File does not exist</h3>");
webpage += F("<a href='/"); webpage += target + "'>[Back]</a><br><br>";
append_page_footer();
SendHTML_Content();
SendHTML_Stop();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void ReportCouldNotCreateFile(String target)
SendHTML_Header();
webpage += F("<h3>Could Not Create Uploaded File (write-protected?)</h3>");
webpage += F("<a href='/"); webpage += target + "'>[Back]</a><br><br>";
append_page_footer();
SendHTML_Content();
SendHTML_Stop();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
String file_size(int bytes)
String fsize = "";
if (bytes < 1024) fsize = String(bytes)+" B";
else if(bytes < (1024*1024)) fsize = String(bytes/1024.0,3)+" KB";
else if(bytes < (1024*1024*1024)) fsize = String(bytes/1024.0/1024.0,3)+" MB";
else fsize = String(bytes/1024.0/1024.0/1024.0,3)+" GB";
return fsize;
- CSS.h文件代码
void append_page_header()
webpage = F("<!DOCTYPE html><html>");
webpage += F("<head>");
webpage += F("<title>File Server</title>"); // NOTE: 1em = 16px
webpage += F("<meta name='viewport' content='user-scalable=yes,initial-scale=1.0,width=device-width'>");
webpage += F("<style>");
webpage += F("bodymax-width:65%;margin:0 auto;font-family:arial;font-size:105%;text-align:center;color:blue;background-color:#F7F2Fd;");
webpage += F("ullist-style-type:none;margin:0.1em;padding:0;border-radius:0.375em;overflow:hidden;background-color:#dcade6;font-size:1em;");
webpage += F("lifloat:left;border-radius:0.375em;border-right:0.06em solid #bbb;last-child border-right:none;font-size:85%");
webpage += F("li adisplay: block;border-radius:0.375em;padding:0.44em 0.44em;text-decoration:none;font-size:85%");
webpage += F("li a:hoverbackground-color:#EAE3EA;border-radius:0.375em;font-size:85%");
webpage += F("section font-size:0.88em;");
webpage += F("h1color:white;border-radius:0.5em;font-size:1em;padding:0.2em 0.2em;background:#558ED5;");
webpage += F("h2color:orange;font-size:1.0em;");
webpage += F("h3font-size:0.8em;");
webpage += F("tablefont-family:arial,sans-serif;font-size:0.9em;border-collapse:collapse;width:85%;");
webpage += F("th,td border:0.06em solid #dddddd;text-align:left;padding:0.3em;border-bottom:0.06em solid #dddddd;");
webpage += F("tr:nth-child(odd) background-color:#eeeeee;");
webpage += F(".rcorners_n border-radius:0.5em;background:#558ED5;padding:0.3em 0.3em;width:20%;color:white;font-size:75%;");
webpage += F(".rcorners_m border-radius:0.5em;background:#558ED5;padding:0.3em 0.3em;width:50%;color:white;font-size:75%;");
webpage += esp8266webserver使用spiffs(spiflashfilesystem)
ESP8266WebServer使用SPIFFS(SPIFlashFileSystem)通过SPIFFS,将WebServer的内容存放在闪存文件系统中,从而省去了,网页代码的转义处理,实现网页页面开发内容和程序代码分离。方便维护和升级以及移植工作。采用的开发板:Nodemcu1.0固件... 查看详情
esp8266webserver实现基本的按键控制io引脚(代码片段)
ESP8266WebServer实现基本的按键控制IO引脚本教程是一个循序渐进的指南,展示了如何构建一个独立的ESP8266WebServer来控制两个输出(两个led)。这个ESP8266NodeMCUWeb服务器是移动响应的,它可以在您的本地网络中的任何带有浏览器的设备... 查看详情
如何在esp8266上实现webserver
...助理解。调试PC接入ESP的softAP中,PC端使用curl工具与ESP的webserver进行http的通信,DEMO中展示了GET和POST两种方法。 查看详情
ESP8266 WebServer如何流式传输无符号字符
】ESP8266WebServer如何流式传输无符号字符【英文标题】:ESP8266WebServerhowtostreamunsignedchar【发布时间】:2017-03-2016:11:47【问题描述】:这个周末我在玩xxd-i将二进制文件转换为无符号字符数组,我想我可以用它来将小的二进制文件嵌... 查看详情
esp8266webserver(websocket)实现多控件多引脚调节(pwm)(代码片段)
ESP8266WebServer(WebSocket)实现多控件多引脚调节(PWM)相关篇《ESP8266LittleFS文件系统》介绍ArduinoIDE安装LittleFS本教程展示了如何使用ESP8266NodeMCU板构建一个web服务器,该服务器可以显示带有多个滑块的网页。滑块通过控制不同PWM信号的... 查看详情
wledandws2812brgbledsstripallinone(代码片段)
...InOneWLEDAppWLEDControlWS2812BandmanymoretypesofdigitalRGBLEDswithanESP8266orESP32overWi-Fi!https://github.com/Aircoookie/WLEDhttps://kno.wled.ge/Wi-Fihttps://en.wikipedia.org/wiki/Wi-FiHomeAssistantWLEDWLEDisafastandfeature-richimplementationofanESP8266/ESP32webservertocontrolNeoPixel(WS2812B,WS281... 查看详情
esp8266使用spiffs进行文件的上传与保存(代码片段)
...混为一谈 附代码#include<ESP8266WiFi.h>#include<ESP8266WebServer.h>#include<ESP8266mDNS.h>#include<FS.h>ESP8266WebServerserver(80);voidsetup()Serial.begin(115200);//putyoursetupcodehere,torunonce:WiFi.begin("kangtine","87602261");SPIFFS.begin();//这个地方要开... 查看详情
本篇更完esp保姆级教程疯狂传感器篇——案例:esp8266+bh1750+webserver(局域网内查看曲线变化图)
忘记过去,超越自己❤️博客主页单片机菜鸟哥,一个野生非专业硬件IOT爱好者❤️❤️本篇创建记录2022-04-24❤️❤️本篇更新记录2022-04-24❤️ 查看详情
ESP32、ESP8266 和 ESP8266 节点 MCU 不工作
】ESP32、ESP8266和ESP8266节点MCU不工作【英文标题】:ESP32,ESP8266,ANDESP8266NODEMCUnotworking【发布时间】:2021-07-1302:09:33【问题描述】:1.我从esp开始。32我使用了arduinoIDE,它只在PORTS中显示COM1。当我上传代码时,我在连接时按下了启动... 查看详情
arduinoesp8266webserve服务端对sd卡文件管理系统
ArduinoESP8266WebServe服务端对SD卡文件管理系统实现的功能是,通过网页端,访问ESP8266,对挂载在ESP8266上的MicroSD卡(安装的是TF小卡,格式FAT32)进行文件下载或者上传,相当于一个微型版的NAS(网络附属存储),当然你也可以利用这... 查看详情
两个服务器在同一个 ESP32 程序上? ESPAsyncWebServer 和 ESP32WebServer
】两个服务器在同一个ESP32程序上?ESPAsyncWebServer和ESP32WebServer【英文标题】:TwoserveronthesameESP32program?ESPAsyncWebServerandESP32WebServer【发布时间】:2021-08-1114:48:00【问题描述】:我正在开发esp32模块,我制作了一个Web界面来显示传感... 查看详情
esp8266网页调控rgb灯(代码片段)
ESP8266网页调控RGB灯控制页面实例代码//ESP8266RGBRemote#include<ESP8266WiFi.h>#include<WiFiClient.h>#include<ESP8266WebServer.h> 查看详情
esp32/esp8266自动下载电路波形,esp32/esp8266不能uart流控自动下载的解决方法
ESP32/ESP8266自动下载电路原理解析瞧这里:ESP8266/ESP32自动下载电路原理分析 其中EN引脚上的RC电路必不可少,如取值不当会导致不能实现自动下载。 经常听人说有ESP32UART自动下载不可用,而换了上电自复位... 查看详情
esp32/esp8266自动下载电路波形,esp32/esp8266不能uart流控自动下载的解决方法
ESP32/ESP8266自动下载电路原理解析瞧这里:ESP8266/ESP32自动下载电路原理分析 其中EN引脚上的RC电路必不可少,如取值不当会导致不能实现自动下载。 经常听人说有ESP32UART自动下载不可用,而换了上电自复位... 查看详情
esp32/esp8266自动下载电路波形,esp32/esp8266不能uart流控自动下载的解决方法
ESP32/ESP8266自动下载电路原理解析瞧这里:ESP8266/ESP32自动下载电路原理分析 其中EN引脚上的RC电路必不可少,如取值不当会导致不能实现自动下载。 经常听人说有ESP32UART自动下载不可用,而换了上电自复位... 查看详情
esp32,esp8266之间wifi互联实验(代码片段)
▌ESP32,ESP8266模块互联ESP32,ESP8266模块具有很丰富的功能,便于设计一些现场需要联网的场合。基于此在AI视觉组基于ESP32的裁判系统第一版本设计要求就使用了ESP32进行相关核心控制器的设计。但是之前对于这些模块之间相互... 查看详情
stm32+esp8266配置(代码片段)
这里简单的记录STM32+ESP8266配置 MCU:STM32F030R8ESP8266模块:ESP-01SESP8266工作模式:WIFIAP、TCPClientMCU、ESP8266互连USART:USART1MCU信息打印USART:USART2(下面有些代码涉及USART2,可以忽略,因为现在是从项目代码中复制出来的,处理... 查看详情
esp32/esp8266webservicehttp添加身份验证(代码片段)
ESP32/ESP8266WebServiceHTTP添加身份验证学习如何使用ArduinoIDE添加用户名和密码的HTTP认证,才能访问ESP32和ESP8266NodeMCUweb服务器项目。如果您键入正确的用户并通过。如果退出登录,只有在输入正确的凭据后才能再次访问。访问流程所... 查看详情