ESP8266:向闪存系统上传文件
本帖最后由 划句顾 于 2021-9-4 09:41 编辑static/image/hrline/5.gif
在上传代码之前,要先将文件下载到esp8266中,再上传代码,不然会因为找不到资源而报错。
static/image/hrline/5.gif
代码:/****
* author:LaoGu
* time:2021/9/3
* purpose;将data里面的文件下载到esp8266里面后,通过8266的网址,查看网页
*/
#include<ESP8266WiFi.h>
#include<ESP8266WiFiMulti.h>
#include<ESP8266WebServer.h>
#include<FS.h>
ESP8266WiFiMulti wifiMulti;
ESP8266WebServer esp8266_server(80);
void setup(){
Serial.begin(9600);
Serial.println("");
wifiMulti.addAP("小G的wife","g5201314");//这里是你自己的WiFi和密码
wifiMulti.addAP("nanjishit","g5201314");
Serial.println("Connecting...");
int i = 0;
while(wifiMulti.run()!=WL_CONNECTED){
delay(1000);
Serial.print(i++); Serial.print(" ");
}
Serial.println("\n");
Serial.print("Connect to ");
Serial.println(WiFi.SSID());
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if(SPIFFS.begin()){
Serial.println("SPIFFS Started.");
}else{
Serial.println("SPIFFS Failed to start.");
}
esp8266_server.begin(); //启动网络服务器
esp8266_server.onNotFound(handleUserRequest);
Serial.println("HTTP server started");
}
void loop(){
esp8266_server.handleClient();//处理用户请求
}
void handleUserRequest(){
//获取用户请求网址信息
String webAddress = esp8266_server.uri();
//通过handleFileRead函数处理用户访问
bool fileReadOK = handleFileRead(webAddress);
//如果在SPIFFS无法找到用户访问的资源,则回复404
if(!fileReadOK){
esp8266_server.send(404,"text/plain","404: Not Found");
}
}
bool handleFileRead(String path){
if(path.endsWith("/")){ //如果访问地址以"/"结尾
path = "/index.html"; //则将访问地址修改为/index.html,便于SPIFFS访问
}
String contentType = getContentType(path);//获取文件类型
if(SPIFFS.exists(path)){
File file = SPIFFS.open(path,"r");
esp8266_server.streamFile(file,contentType);//并且将该文件返回浏览器
file.close();
return true;
}
return false;
}
String getContentType(String filename){
if(filename.endsWith(".htm")) return "text/html";
else if(filename.endsWith(".html")) return "text/html";
else if(filename.endsWith(".css"))return "text/css";
else if(filename.endsWith(".js")) return "application/javascript";
else if(filename.endsWith(".png")) return "image/png";
else if(filename.endsWith(".gif")) return "image/gif";
else if(filename.endsWith(".jpg")) return "image/jpeg";
else if(filename.endsWith(".ico")) return "image/x-icon";
else if(filename.endsWith(".xml")) return "text/xml";
else if(filename.endsWith(".pdf")) return "application/x-pdf";
else if(filename.endsWith(".zip")) return "application/x-zip";
else if(filename.endsWith(".gz"))return "application/x-gzip";
return "text/plain";
}
static/image/hrline/5.gif
串口:
static/image/hrline/5.gif
复制网址:192.168.43.109 到和esp8266相同局域网中的手机或者电脑的浏览器 打开
static/image/hrline/5.gif
效果如下:
static/image/hrline/5.gif
注:图片等资源必须用英文命名,用中文到时候浏览器显示不出来。
页:
[1]