上位に戻る ESP32 ブラウザからSPIFFS領域にファイルアップロード 初版2025/07/23

Arudino IDEで、SPIFFSの領域にファイルを書き込むのに、ESP32 Sketch Data Uploadを使っていましたが、これ、IDEの
バージョンV2.Xでは、動かず、いちいちV1.Xで使っていました。今回ちょこちょこファイルを書き換えたいので、Webサーバを立ち上げて
ブラウザからファイルを書き込めるようにしてみました

参考サイト
ESP32 ブラウザからアップロードでアプリ更新|えぬでんき

ESP32 / 8266 無線でスケッチ & SPIFFS アップロード!!|Rcat999

  1. どんな感じ




  2. 必要ライブラリ
    GitHub - espressif/arduino-esp32: Arduino core for the ESP32



  3. コード
    espressifから提供されています標準ライブラリの、OTAWebUpdaterを利用しています スケッチのアップロードですが
    SPIFFSの領域に書き込むようにしています
    HTMLの記述の仕方が、ライブラリそのまま利用しているので、自分の書き方と違っていてバラバラになってます すいません
    SPIFFSの領域がフォーマットされていないと、初期化するので、この時ウオッチドッグタイマーに引っかかてエラーがでますが
    気にせず終了するのを待ってください
    #include <WiFi.h>
    #include <WiFiClient.h>
    #include <WebServer.h>
    #include <Update.h>
    #include <FS.h>
    #include <SPIFFS.h>

    // Wi-Fi接続情報を入力
    const char* ssid     ="anatanoSSID";
    const char* password = "anatano_password";
    const IPAddress ip(xxx,xxx,xxx,xxx);
    const IPAddress gateway(192,168,xxx,xxx);
    const IPAddress subnet(255,255,255, 0);
    const IPAddress dns1(192,168,xxx,xxx);
    //wifi接続
    int lpcnt;
    int lpcnt2;

    static WebServer server(80);


    /*
     * Server Index Page
     */

    const char* serverIndex =
    "<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>"
    "<form method='POST' action='#' enctype='multipart/form-data' id='upload_form'>"
       "<input type='file' name='update'>"
            "<input type='submit' value='Update'>"
        "</form>"
     "<div id='prg'>progress: 0%</div>"
     "<script>"
      "$('form').submit(function(e){"
      "e.preventDefault();"
      "var form = $('#upload_form')[0];"
      "var data = new FormData(form);"
      " $.ajax({"
      "url: '/update',"
      "type: 'POST',"
      "data: data,"
      "contentType: false,"
      "processData:false,"
      "xhr: function() {"
      "var xhr = new window.XMLHttpRequest();"
      "xhr.upload.addEventListener('progress', function(evt) {"
      "if (evt.lengthComputable) {"
      "var per = evt.loaded / evt.total;"
      "$('#prg').html('progress: ' + Math.round(per*100) + '%');"
      "}"
      "}, false);"
      "return xhr;"
      "},"
      "success:function(d, s) {"
      "console.log('success!')"
     "},"
     "error: function (a, b, c) {"
     "}"
     "});"
     "});"
     "</script>";



    void setup() {
      // put your setup code here, to run once:
      Serial.begin(115200);
     // ssidとpasswordを用いてWi-Fiに接続
      Serial.print("Connecting to ");
      Serial.println(ssid);
      if (!WiFi.config(ip,gateway,subnet,dns1)){
         Serial.println("Failed to configure!");
      }
       while (WiFi.status() != WL_CONNECTED) {    // 接続確認
          delay(500);                            //   0.5秒毎にチェック
          lpcnt += 1 ;                           //
          if (lpcnt > 6) {                       // 6回目(3秒) で切断/再接続
            WiFi.disconnect(true,true) ;
            WiFi.config(ip,gateway,subnet,dns1);        //
            WiFi.begin(ssid, password);    //
            lpcnt = 0 ;                          //
            lpcnt2 += 1 ;                        // 再接続の回数をカウント
          }                                      //
          if (lpcnt2 > 3) {                      // 3回 接続できなければ、
            ESP.restart() ;                      // ソフトウェアリセット
          }                                      //
          Serial.print(".");                     //
      }            
     
      // IPアドレスを出力
      Serial.println("");
      Serial.println("WiFi connected.");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
      // initialize SPIFFS
      if (!SPIFFS.begin(true)) {
        Serial.println("SPIFFSをフォーマットします");
        SPIFFS.format();
        if (!SPIFFS.begin(true)) {
          Serial.println("SPIFFSを利用できません");
        }
        return;
      }

        server.on("/", shokipage);      //TOPページのアドレスにアクセスしたときの処理関数

        server.on("/serverIndex", HTTP_GET, []() {
            server.sendHeader("Connection", "close");
            server.send(200, "text/html", serverIndex);
        });

        server.on("/update", HTTP_POST, []() {
                Serial.printf("Update start\n");
                server.sendHeader("Connection", "close");
                server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
                Serial.printf("Update end\n");
            },
            []() {
                HTTPUpload& upload = server.upload();
                String NN = "/";
                NN += upload.filename;
                if (upload.status == UPLOAD_FILE_START) {
                 File file = SPIFFS.open(NN, "w");
                file.close();
                } else if (upload.status == UPLOAD_FILE_WRITE) {
                  File file = SPIFFS.open(NN, "a"); //a append 追記モード
                 file.write(&upload.buf[0], upload.currentSize);
                 file.close();
                } else if (upload.status == UPLOAD_FILE_END) {
                  server.send(200, "text/plain", "OK");
                }
                yield(); //watchdogタイマー監視回避用
             });
        server.begin();
    }

    void shokipage() {

      String html;
     
      //HTML記述
      html = "<!DOCTYPE html>\n";
      html += "<html lang='ja'>\n";
      html += "<head>\n";
      html += "<meta charset=\"utf-8\">\n";
      html += "<META name=\"viewport\" content=\"width=399\">\n";
      html += "<title>時計設定</title>\n";
      html += "</head>\n";
      html += "<body>\n";
      html += "<center><h1>時計設定</h1></center><p>\n";
      html += "<hr><p>\n";
      html += "<p><button type=\"button\" onclick=\"location.href='/serverIndex'\">データアップロード</button></p>";
      html += "</p></body>\n";
      html += "</html>\n";

      // HTMLを出力する
      server.send(200, "text/html", html);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      server.handleClient();
      delay(1);
    }





    以上間違い等ありましたら、以下ご意見箱にお願いします

   

    ご意見箱