Arduino ESP32 Web服务器SD卡文件管理
Posted perseverance52
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Arduino ESP32 Web服务器SD卡文件管理相关的知识,希望对你有一定的参考价值。
Arduino ESP32 Web服务器SD卡文件管理
本示例来自官方示例,如果直接使用,会有问题,找不到SD卡,这一点坑了好久,排查的时候排查接线排查卡,更换程序又可以找到,确定是程序代码问题。
程序代码
/*
SDWebServer - Example WebServer with SD Card backend for esp8266
Copyright (c) 2015 Hristo Gochkov. All rights reserved.
This file is part of the WebServer library for Arduino environment.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Have a FAT Formatted SD Card connected to the SPI port of the ESP8266
The web root is the SD Card root folder
File extensions with more than 3 charecters are not supported by the SD Library
File Names longer than 8 charecters will be truncated by the SD library, so keep filenames shorter
index.htm is the default index (works on subfolders as well)
upload the contents of SdRoot to the root of the SDcard and access the editor by going to http://esp8266sd.local/edit
*/
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>
#include <SPI.h>
#include <SD.h>
#include "FS.h"
#define Serial Serial
const char* ssid = "MERCURY_D268G";
const char* password = "pba5ayzk";
const char* host = "esp32sd";
WebServer server(80);
static bool hasSD = false;
File uploadFile;
#define DBG_OUTPUT_PORT Serial
String wifissid = "";
String wifipwd = "";
/******容量转换*******/
String formatBytes(size_t bytes)
if (bytes < 1024)
return String(bytes) + "B";
else if (bytes < (1024 * 1024))
return String(bytes / 1024.0) + "KB";
else if (bytes < (1024 * 1024 * 1024))
return String(bytes / 1024.0 / 1024.0) + "MB";
else
return String(bytes / 1024.0 / 1024.0 / 1024.0) + "GB";
/******查看SD卡文件列表*******/
void listDir(fs::FS &fs, const char * dirname, uint8_t levels)
Serial.printf("Listing directory: %s\\n", dirname);
File root = fs.open(dirname);
if(!root)
Serial.println("Failed to open directory");
return;
if(!root.isDirectory())
Serial.println("Not a directory");
return;
File file = root.openNextFile();
while(file)
if(file.isDirectory())
Serial.print(" DIR : ");
Serial.println(file.name());
if(levels)
listDir(fs, file.name(), levels -1);
else
Serial.print(" FILE: ");
Serial.print(file.name());
Serial.print(" SIZE: ");
Serial.println(file.size());
file = root.openNextFile();
/******SD卡创建文件夹*******/
void createDir(fs::FS &fs, const char * path)
Serial.printf("Creating Dir: %s\\n", path);
if(fs.mkdir(path))
Serial.println("Dir created");
else
Serial.println("mkdir failed");
/******删除SD卡中的文件夹*******/
void removeDir(fs::FS &fs, const char * path)
Serial.printf("Removing Dir: %s\\n", path);
if(fs.rmdir(path))
Serial.println("Dir removed");
else
Serial.println("rmdir failed");
/******读取SD卡中的文件*******/
void readFile(fs::FS &fs, const char * path)
Serial.printf("Reading file: %s\\n", path);
File file = fs.open(path);
if(!file)
Serial.println("Failed to open file for reading");
return;
Serial.print("Read from file: ");
while(file.available())
Serial.write(file.read());
file.close();
/******向SD卡中的文件写数据*******/
void writeFile(fs::FS &fs, const char * path, const char * message)
Serial.printf("Writing file: %s\\n", path);
File file = fs.open(path, FILE_WRITE);
if(!file)
Serial.println("Failed to open file for writing");
return;
if(file.print(message))
Serial.println("File written");
else
Serial.println("Write failed");
file.close();
/******向SD卡中的文件中添加数据*******/
void appendFile(fs::FS &fs, const char * path, const char * message)
Serial.printf("Appending to file: %s\\n", path);
File file = fs.open(path, FILE_APPEND);
if(!file)
Serial.println("Failed to open file for appending");
return;
if(file.print(message))
Serial.println("Message appended");
else
Serial.println("Append failed");
file.close();
/******给SD卡中的文件重命名*******/
void renameFile(fs::FS &fs, const char * path1, const char * path2)
Serial.printf("Renaming file %s to %s\\n", path1, path2);
if (fs.rename(path1, path2))
Serial.println("File renamed");
else
Serial.println("Rename failed");
/******删除SD卡中的文件*******/
void deleteFile(fs::FS &fs, const char * path)
Serial.printf("Deleting file: %s\\n", path);
if(fs.remove(path))
Serial.println("File deleted");
else
Serial.println("Delete failed");
/******测试SD卡读写*******/
void testFileIO(fs::FS &fs, const char * path)
File file = fs.open(path);
static uint8_t buf[512];
size_t len = 0;
uint32_t start = millis();
uint32_t end = start;
if(file)
len = file.size();
size_t flen = len;
start = millis();
while(len)
size_t toRead = len;
if(toRead > 512)
toRead = 512;
file.read(buf, toRead);
len -= toRead;
end = millis() - start;
Serial.printf("%u bytes read for %u ms\\n", flen, end);
file.close();
else
Serial.println("Failed to open file for reading");
file = fs.open(path, FILE_WRITE);
if(!file)
Serial.println("Failed to open file for writing");
return;
size_t i;
start = millis();
for(i=0; i<2048; i++)
file.write(buf, 512);
end = millis() - start;
Serial.printf("%u bytes written for %u ms\\n", 2048 * 512, end);
file.close();
/******客户端网页回调函数*******/
void returnOK()
server.send(200, "text/plain", "");
void returnOK(String msg)
server.send(200, "text/plain", msg+"\\r\\n");
void returnFail(String msg)
server.send(500, "text/plain", msg + "\\r\\n");
bool loadFromSdCard(String path)
String dataType = "text/plain";
if (path.endsWith("/"))
path += "index.htm";
if (path.endsWith(".src"))
path = path.substring(0, path.lastIndexOf("."));
else if (path.endsWith(".htm"))
dataType = "text/html";
else if (path.endsWith(".css"))
dataType = "text/css";
else if (path.endsWith(".js"))
dataType = "application/javascript";
else if (path.endsWith(".png"))
dataType = "image/png";
else if (path.endsWith(".gif"))
dataType = "image/gif";
else if (path.endsWith(".jpg"))
dataType = "image/jpeg";
else if (path.endsWith(".ico"))
dataType = "image/x-icon";
else if (path.endsWith(".xml"))
dataType = "text/xml";
else if (path.endsWith(".pdf"))
dataType = "application/pdf";
else if (path.endsWith(".zip"))
dataType = "application/zip";
File dataFile = SD.open(path.c_str());
if (dataFile.isDirectory())
path += "/index.htm";
dataType = "text/html";
dataFile = SD.open(path.c_str());
if (!dataFile)
return false;
if (server.hasArg("download"))
dataType = "application/octet-stream";
if (server.streamFile(dataFile, dataType) != dataFile.size())
DBG_OUTPUT_PORT.println("Sent less data than expected!");
dataFile.close();
return true;
/******客户端获取wifi信息回调函数*******/
void handleWifiPage()
String content = "<html><body>Congratulations! You Now Connect to The Wifi!<br>";
content += "You Connect Wifi Name is:"+String(ssid)+"<br>";
content += "Wifi Password is:"+String(password)+"<br>";
content += "You input ssid is:" + wifissid + "<br>";
content += "You input password is:"+wifipwd+"<br>";
content += "</body></html>";
server.send(200, "text/html", content);
/******客户端设置wifi信息*******/
void handleSetWifi()
String msg;
if (server.hasArg("DISCONNECT"))
Serial.println("Disconnection");
String header = "HTTP/1.1 301 OK\\r\\nSet-Cookie: ESPSESSIONID=0\\r\\nLocation: /wifiinfo\\r\\nCache-Control: no-cache\\r\\n\\r\\n";
server.sendContent(header);
return;
if (server.hasArg("WIFINAME") && server.hasArg("WIFIPWD"))
wifissid=server.arg("WIFINAME");
wifipwd=server.arg("WIFIPWD");
String header = "HTTP/1.1 301 OK\\r\\nSet-Cookie: ESPSESSIONID=1\\r\\nLocation: /wifiinfo\\r\\nCache-Control: no-cache\\r\\n\\r\\n";
server.sendContent(header);
Serial.println("WIFI INFO:");
Serial.println("Wifi Name:"+wifissid);
Serial.println("Wifi Password:"+wifipwd);
if(WiFi.isConnected())
WiFi.disconnect();
WiFi.begin(wifissid.c_str(),wifipwd.c_str());
int i=0;
while (WiFi.status() != WL_CONNECTED && i++ < 50) //wait 25 seconds
Serial.print(".");
delay(500);
if (i Arduino ESP8266 Web服务端SD卡文件管理系统V1.1
Arduino ESP32 Web服务器从microSD卡读取