ndfweb.cn

ESP8266 使用 SPIFFS 进行文件的上传与保存


2021-07-02 22:18:53 (4128)


首先需要下载包。网址https://github.com/esp8266/arduino-esp8266fs-plugin/releases  我下载的是最新的包。

下载下来之后是个jar包,需要放到arduino根目录的tools文件夹中。

 

 

不要放错位置。放错位置的话,你的arduino IDE是无法在工具栏看到这个的,切记。我一开始就是放错了位置,结果找不到

然后呢,你需要在项目里创建一个data文件夹。然后将需要上传到falsh中的文件放到这个目录中。然后点击上面Data Upload就可以把这些文件上传到falsh中了

注意:上传项目编译文件是编译文件,上传data目录文件是目录文件。两码事,千万不要混为一谈

 

附代码

复制代码

#include <ESP8266WiFi.h>#include <ESP8266WebServer.h>#include <ESP8266mDNS.h>#include <FS.h>ESP8266WebServer server(80);void setup() {
  Serial.begin(115200);  // put your setup code here, to run once:
  WiFi.begin("kangtine","87602261");  SPIFFS.begin();//这个地方要开启  while(WiFi.status()!=WL_CONNECTED){
      delay(500);
      Serial.println(".");
    }
          Serial.print("dns 配置中");    if(WiFi.status() == WL_CONNECTED) //If WiFi connected to hot spot then start mDNS  {    if (MDNS.begin("lsq")) {  //Start mDNS with name esp8266
      Serial.println("MDNS started");
    }
  }
    Serial.print("Wi-Fi connected,IP:");
    Serial.println(WiFi.localIP());
    server.on("/",[](){
        server.send(200,"text/html","hello from <b>ESP8266</b>.");
      });
   server.on("/index.htm",rootRouter);
     server.onNotFound([](){
        server.send(404,"text/plain","File Not found!");
      });
    server.begin();

    MDNS.addService("http","tcp",80);
    Serial.println("HTTP server started.");    int n = MDNS.queryService("http","tcp");    if(n>0){        for(int i=0;i<n;i++){
            Serial.print(i+1);
            Serial.print(MDNS.hostname(i));
            Serial.print(MDNS.IP(i));
            Serial.print(MDNS.port(i));
          }
      }else{
          Serial.print("no service found");
        }
}void loop() {  // put your main code here, to run repeatedly:    MDNS.update();
  server.handleClient();
}void rootRouter(){    File file=SPIFFS.open("/index.htm","r");//以只读模式打开index.htm,流模式为text/html。然后关闭该文件
    server.streamFile(file,"text/html");
    file.close();
  }

复制代码

 

至此就可以了。记得把index.htm放到data文件夹中,然后点击Data Upload上传

注意,如果你的index.htm里边引用了别的文件或者图片。那必须在server.on()中设置

例如,如果你的index.htm中引用了某个图片。

server.on("/img/aaa.png",imgRouter);

void imgRouter(){

  

 File file=SPIFFS.open("/img/aaa.png","r");//以只读模式打开index.htm,流模式为text/html。然后关闭该文件
    server.streamFile(file,"image/png");
    file.close();

}

这样来操作才可以。相当的麻烦好像。。。不过貌似有好的办法。。。

 

接下来让我们认识SPIFFS文件系统

 

 

 

 

 

 

 Dir  目录对象

用法

next 下一个文件   fileName 读取文件名  openFile 打开文件

Dir dir=SPIFFS.openDir("/data");

while(dir.next)){

  Serial.print(dir.fileName());

  File f = dir.openFile("r");

  Serial.println(f.size());

}

 

 

File (文件)对象

 SPIFFS.open 和 dir.openFile 都会返回File对象,他支持stream的所有函数。你可以使用readBytes findUntil   parseInt  println及其他所有stream方法

 

 

  返回目前文件的位置,单位是byte

 


了解更多请访问:http://www.ndfweb.cn/news-874.html
  NDF俱乐部
  国际域名注册
  建站咨询
合作伙伴:万网 | 新网 | 新网互联 NDF网站建设淘宝店 | 实用工具 | 外貿網站建設 | 联系我们
鲁公网安备 37110202000336号 鲁ICP备2021027697号-1 Sitemap - RSSRSS订阅