ESP-32 笔记(3)https 实现从url中下载文件

#include <stdio.h>
#include <string.h>
#include "esp_http_client.h"

#define FILE_URL "http://example.com/file.txt"
#define FILE_PATH "/spiffs/downloaded_file.txt"

esp_err_t http_event_handler(esp_http_client_event_t *evt)
{
    switch(evt->event_id) {
        case HTTP_EVENT_ERROR:
            printf("HTTP_EVENT_ERROR\n");
            break;
        case HTTP_EVENT_ON_CONNECTED:
            printf("HTTP_EVENT_ON_CONNECTED\n");
            break;
        case HTTP_EVENT_HEADER_SENT:
            printf("HTTP_EVENT_HEADER_SENT\n");
            break;
        case HTTP_EVENT_ON_HEADER:
            printf("HTTP_EVENT_ON_HEADER, key=%s, value=%s\n", evt->header_key, evt->header_value);
            break;
        case HTTP_EVENT_ON_DATA:
            printf("HTTP_EVENT_ON_DATA, len=%d\n", evt->data_len);
            if (!esp_http_client_is_chunked_response(evt->client)) {
                // Write received data to a file
                FILE* f = fopen(FILE_PATH, "a");
                if (f == NULL) {
                    printf("Failed to open file for writing\n");
                    return ESP_FAIL;
                }
                fwrite(evt->data, 1, evt->data_len, f);
                fclose(f);
            }
            break;
        case HTTP_EVENT_ON_FINISH:
            printf("HTTP_EVENT_ON_FINISH\n");
            break;
        case HTTP_EVENT_DISCONNECTED:
            printf("HTTP_EVENT_DISCONNECTED\n");
            break;
    }
    return ESP_OK;
}

void download_file_task(void *pvParameters)
{
    esp_http_client_config_t config = {
        .url = FILE_URL,
        .event_handler = http_event_handler,
    };
    esp_http_client_handle_t client = esp_http_client_init(&config);

    // Set up file to store the downloaded data
    FILE* f = fopen(FILE_PATH, "w");
    if (f == NULL) {
        printf("Failed to create file for writing\n");
        return;
    }
    fclose(f);

    esp_err_t err = esp_http_client_perform(client);
    if (err == ESP_OK) {
        printf("File downloaded successfully\n");
    } else {
        printf("File download failed\n");
    }

    esp_http_client_cleanup(client);

    vTaskDelete(NULL);
}

void app_main()
{
    // Initialize SPIFFS file system (if necessary)

    xTaskCreate(&download_file_task, "download_file_task", 4096, NULL, 5, NULL);
}

此示例使用ESP-IDF的HTTP客户端库(esp_http_client)来下载文件。您需要将FILE_URL更改为要下载的文件的URL,并将FILE_PATH更改为要将文件保存到的路径。在示例中,我使用SPIFFS文件系统,并在app_main函数中添加了初始化SPIFFS的注释。您可以根据自己的需求进行修改。

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值