本站改版新增arduino频道
arduino http 下载文件保存spiffs
#include <WiFi.h>
#include <HTTPClient.h>
#include <SPIFFS.h>
#include <Arduino.h>
#include <esp_heap_caps.h>
const char* ssid = "NBWIFI";
const char* password = "z7758521";
const char* url = "https://www.esp56.com/12300000/index.html";
void setup() {
Serial.begin(115200);
Serial.printf("Deafult free size: %d\n", heap_caps_get_free_size(MALLOC_CAP_DEFAULT));
Serial.printf("PSRAM free size: %d\n", heap_caps_get_free_size(MALLOC_CAP_SPIRAM));
// 连接 WiFi
// 连接 WiFi
WiFi.begin(ssid, password);
Serial.print("正在连接 Wi-Fi");
// 检测是否连接成功
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("连接成功");
Serial.print("IP 地址:");
Serial.println(WiFi.localIP());
// 挂载 SPIFFS
if (!SPIFFS.begin(true)) {
Serial.println("An error has occurred while mounting SPIFFS");
return;
}
// 创建 HTTPClient 对象
HTTPClient http;
// 开始下载
http.begin(url);
int httpCode = http.GET();
if (httpCode > 0) {
String txt = http.getString(); // Get the request response payload
Serial.println(txt);
// 打开文件进行写入
File file = SPIFFS.open("/index.html", FILE_WRITE);
if (!file) {
Serial.println("Failed to open file for writing");
return;
}
// 获取响应体并写入文件
// 将字符串写入到文件中
file.print(txt);
// 关闭文件
file.close();
Serial.println("File downloaded and saved");
} else {
Serial.printf("Failed to download file, HTTP error code: %d\n", httpCode);
}
// 检查文件是否存在
if (SPIFFS.exists("/index.html")) {
// 打开文件进行读取
File file = SPIFFS.open("/index.html", FILE_READ);
if (!file) {
Serial.println("Failed to open file for reading");
return;
}
Serial.println("文件存在");
Serial.print("index.html的大小:");
Serial.println(file.size());
// 读取并输出文件内容
String content = file.readString();
Serial.println(content);
// 关闭文件
file.close();
} else {
Serial.println("File does not exist");
}
Serial.printf("SPIFFS的总体积: %d 字节\r\n", SPIFFS.totalBytes()/1024);
Serial.printf("SPIFFS的已用体积: %d 字节\r\n", SPIFFS.usedBytes()/1024);
//SPIFFS.end();
Serial.printf("Deafult free size: %d\n", heap_caps_get_free_size(MALLOC_CAP_DEFAULT));
Serial.printf("PSRAM free size: %d\n", heap_caps_get_free_size(MALLOC_CAP_SPIRAM));
delay(10000);
// 关闭 HTTP 连接
http.end();
}
void loop() {
// 主循环代码...
Serial.printf("Deafult free size: %d\n", heap_caps_get_free_size(MALLOC_CAP_DEFAULT));
Serial.printf("PSRAM free size: %d\n", heap_caps_get_free_size(MALLOC_CAP_SPIRAM));
delay(10000);
}
Copyright © 2014 ESP56.com All Rights Reserved
晋ICP备14006235号-22 晋公网安备14108102001165号
执行时间: 0.0093979835510254 seconds