web upload
authorkyz <kyz@kyz.pub>
Wed, 5 Nov 2025 09:31:34 +0000 (17:31 +0800)
committerkyz <kyz@kyz.pub>
Wed, 5 Nov 2025 09:31:34 +0000 (17:31 +0800)
src/user_web_server.c
test-bms.html

index 484098186adec224dbdef10709038c66d0446a93..0a34fb589440c15dbaa41540c1283e520405c934 100644 (file)
@@ -59,6 +59,10 @@ struct pss {
        char *url;
        char *post_body;
        size_t post_body_len;
+
+       char filename[128];             /* the filename of the uploaded file */
+       unsigned long long file_length; /* the amount of bytes uploaded */
+       int fd;                         /* fd on file being saved */
 };
 
 #define RING_DEPTH 4096
@@ -66,8 +70,56 @@ struct pss {
 
 static int interrupted, options;
 
-int ws_received_data_handle(struct lws *wsi, const char *data, size_t len, char **p_resp );
-int http_received_data_handle(struct lws *wsi, const char *data, size_t len, char **p_resp);
+static int
+file_upload_cb(void *data, const char *name, const char *filename,
+              char *buf, int len, enum lws_spa_fileupload_states state)
+{
+       struct pss *pss = (struct pss *)data;
+
+       switch (state) {
+       case LWS_UFS_OPEN:
+               /* take a copy of the provided filename */
+               lws_strncpy(pss->filename, filename, sizeof(pss->filename) - 1);
+               /* remove any scary things like .. */
+               lws_filename_purify_inplace(pss->filename);
+               /* open a file of that name for write in the cwd */
+               pss->fd = lws_open(pss->filename, O_CREAT | O_TRUNC | O_RDWR, 0600);
+               if (pss->fd == -1) {
+                       lwsl_notice("Failed to open output file %s\n",
+                                   pss->filename);
+                       return 1;
+               }
+               break;
+       case LWS_UFS_FINAL_CONTENT:
+       case LWS_UFS_CONTENT:
+               if (len) {
+                       int n;
+
+                       pss->file_length += (unsigned int)len;
+
+                       n = (int)write(pss->fd, buf, (unsigned int)len);
+                       if (n < len) {
+                               lwsl_notice("Problem writing file %d\n", errno);
+                       }
+               }
+               if (state == LWS_UFS_CONTENT)
+                       /* wasn't the last part of the file */
+                       break;
+
+               /* the file upload is completed */
+
+               lwsl_user("%s: upload done, written %lld to %s\n", __func__,
+                         pss->file_length, pss->filename);
+
+               close(pss->fd);
+               pss->fd = -1;
+               break;
+       case LWS_UFS_CLOSE:
+               break;
+       }
+
+       return 0;
+}
 
 /* 销毁 WebSocket 消息 */
 static void __minimal_destroy_message(void *_msg) {
@@ -319,6 +371,8 @@ static int callback_http(struct lws *wsi, enum lws_callback_reasons reason, void
        *p = start, *end = &buf[sizeof(buf) - 1];
        int json_len;
        const char *json_response = NULL;
+    char content_type_buf[256];
+    int content_type = 0;
 
        switch (reason) {
                case LWS_CALLBACK_HTTP:
@@ -371,15 +425,18 @@ static int callback_http(struct lws *wsi, enum lws_callback_reasons reason, void
                                }
                        }else if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI)) {
                                /* 增加 POST 请求专用路径 */
-                               if( strstr( in, "api" ) ){
+                               if( strstr( in, "api" ) || strstr( in, "upload") ){
                                        if( pss->url ){
                                                free( pss->url );
                                        }
                                        pss->url = strdup((const char *)in);
                                        return 0;
                                }
-                               if (!strcmp((const char *)in, "/api/post")) {
-                                       // POST 请求将通过后续的回调处理
+                               if (strstr((const char *)in, "/api/post")) {
+
+                               }else if (strstr((const char *)in, "upload")) {
+
+                }else{
                                        return 0;
                                }
                        } else {
@@ -390,26 +447,49 @@ static int callback_http(struct lws *wsi, enum lws_callback_reasons reason, void
 
                case LWS_CALLBACK_HTTP_BODY:
                        /* 处理 POST 请求体 */
-                       if (!pss->post_body) {
-                               pss->post_body = malloc(len + 1);
-                               if (!pss->post_body) {
-                                       return -1;
-                               }
-                               memcpy(pss->post_body, in, len);
-                               pss->post_body[len] = '\0';
-                               pss->post_body_len = len;
-                       } else {
-                               char *new_body = realloc(pss->post_body, pss->post_body_len + len + 1);
-                               if (!new_body) {
-                                       free(pss->post_body);
-                                       pss->post_body = NULL;
-                                       return -1;
-                               }
-                               pss->post_body = new_body;
-                               memcpy(pss->post_body + pss->post_body_len, in, len);
-                               pss->post_body[pss->post_body_len + len] = '\0';
-                               pss->post_body_len += len;
-                       }
+                //multipart/form-data application/json
+            content_type = 0;
+            if (lws_hdr_copy(wsi, content_type_buf, sizeof(content_type_buf), WSI_TOKEN_HTTP_CONTENT_TYPE)>0 ){
+                printf( "------LWS_CALLBACK_HTTP_BODY-----content_type:%s------------------\n", content_type_buf );
+                if(  strstr( content_type_buf, "multipart/form-data" ) ){
+                    content_type = 1; //upload
+                }else if(  strstr( content_type_buf, "application/json" ) ){
+                    content_type = 2; //json
+                }
+            }
+
+            if( content_type == 2 ){
+                //json
+                if (!pss->post_body) {
+                    pss->post_body = malloc(len + 1);
+                    if (!pss->post_body) {
+                        return -1;
+                    }
+                    memcpy(pss->post_body, in, len);
+                    pss->post_body[len] = '\0';
+                    pss->post_body_len = len;
+                } else {
+                    char *new_body = realloc(pss->post_body, pss->post_body_len + len + 1);
+                    if (!new_body) {
+                        free(pss->post_body);
+                        pss->post_body = NULL;
+                        return -1;
+                    }
+                    pss->post_body = new_body;
+                    memcpy(pss->post_body + pss->post_body_len, in, len);
+                    pss->post_body[pss->post_body_len + len] = '\0';
+                    pss->post_body_len += len;
+                }
+            }else if( content_type == 1 ){
+                //upload
+                if (!pss->spa) {
+                    pss->spa = lws_spa_create(wsi, NULL, 0, 1024, file_upload_cb, pss);
+                    if (!pss->spa)
+                        return -1;
+                }
+                if (lws_spa_process(pss->spa, in, (int)len))
+                    return -1;
+            }
                        break;
 
                case LWS_CALLBACK_CLOSED_CLIENT_HTTP:
@@ -422,119 +502,159 @@ static int callback_http(struct lws *wsi, enum lws_callback_reasons reason, void
                        break;
 
                case LWS_CALLBACK_HTTP_BODY_COMPLETION:
-                       /* 构建 JSON 响应 */
-                       if (pss->post_body) {
-                               char *resp = NULL;
-                               char *text1 = NULL;
-                               char *send = NULL;
-                               printf("接收到的JSON请求体: %s\n", pss->post_body);
-
-                               // 使用cJSON解析JSON格式的请求体
-                               if( process_http_post_message(pss->url, pss->post_body, pss->post_body_len, &resp) == 0){
-                                       // 调试输出,查看解析后的参数
-                                       printf( "process http post msg, resp[%s]\n", resp );
-
-
-                                               char *json_body = resp;
-                                               json_len = json_body ? strlen(json_body) : 0;
-
-                                               /* 重置缓冲区指针用于HTTP头 */
-                                               p = start;
-
-                                               /* 设置 HTTP 头 */
-                                               if (lws_add_http_common_headers(wsi, HTTP_STATUS_OK, "application/json",
-                                                                       json_len, &p, end) < 0) {
-                                                       printf("设置HTTP头失败\n");
-                                               if (json_body) free(json_body);
-                                                       return -1;
-                                               }
-                                               if (lws_finalize_write_http_header(wsi, start, &p, end) < 0) {
-                                                       printf("写入HTTP头失败\n");
-                                                       if (json_body) free(json_body);
-                                                       return -1;
-                                               }
-
-                                               /* 写入 JSON 响应体 */
-                                               if (lws_write(wsi, (unsigned char *)json_body, json_len, LWS_WRITE_HTTP_FINAL) < 0) {
-                                                       printf("写入响应体失败\n");
-                                                       if (json_body) free(json_body);
-                                                       return -1;
-                                               }
-                                               printf("成功返回JSON响应: %s\n", json_body);
-
-                                               // 释放资源
-                                               free(json_body);
-
-                               } else {
-                                       /* JSON解析失败 */
-                                       printf("JSON解析失败\n");
-                                       // 使用cJSON构建错误响应
-                                       cJSON *root = cJSON_CreateObject();
-                                       if (root) {
-                                               cJSON_AddStringToObject(root, "method", "POST");
-                                               cJSON_AddStringToObject(root, "status", "error");
-                                               cJSON_AddStringToObject(root, "message", "Invalid JSON format");
-
-                                               json_response = cJSON_PrintUnformatted(root);
-                                               json_len = json_response ? strlen(json_response) : 0;
-                                       }
-
-                                       if (lws_add_http_common_headers(wsi, HTTP_STATUS_BAD_REQUEST, "application/json",
-                                                               json_len, &p, end) < 0) {
-                                               if (root) cJSON_Delete(root);
-                                               if (json_response) free((void*)json_response);
-                                               return -1;
-                                       }
-                                       if (lws_finalize_write_http_header(wsi, start, &p, end) < 0) {
-                                               if (root) cJSON_Delete(root);
-                                               if (json_response) free((void*)json_response);
-                                               return -1;
-                                       }
-                                       if (lws_write(wsi, (unsigned char *)json_response, json_len, LWS_WRITE_HTTP_FINAL) < 0) {
-                                               if (root) cJSON_Delete(root);
-                                               if (json_response) free((void*)json_response);
-                                               return -1;
-                                       }
-
-                                       // 释放资源
-                                       if (root) cJSON_Delete(root);
-                                       if (json_response) free((void*)json_response);
-                               }
-                       } else {
-                               /* 如果没有请求体,返回默认的JSON响应 */
-
-                               // 使用cJSON构建错误响应
-                               cJSON *root = cJSON_CreateObject();
-                               if (root) {
-                                       cJSON_AddStringToObject(root, "method", "POST");
-                                       cJSON_AddStringToObject(root, "status", "error");
-                                       cJSON_AddStringToObject(root, "message", "No request body received");
-
-                                       json_response = cJSON_PrintUnformatted(root);
-                                       json_len = json_response ? strlen(json_response) : 0;
-                               }
-
-                               if (lws_add_http_common_headers(wsi, HTTP_STATUS_BAD_REQUEST, "application/json",
-                                                       json_len, &p, end) < 0) {
-                                       if (root) cJSON_Delete(root);
-                                       if (json_response) free((void*)json_response);
-                                       return -1;
-                               }
-                               if (lws_finalize_write_http_header(wsi, start, &p, end) < 0) {
-                                       if (root) cJSON_Delete(root);
-                                       if (json_response) free((void*)json_response);
-                                       return -1;
-                               }
-                               if (lws_write(wsi, (unsigned char *)json_response, json_len, LWS_WRITE_HTTP_FINAL) < 0) {
-                                       if (root) cJSON_Delete(root);
-                                       if (json_response) free((void*)json_response);
-                                       return -1;
-                               }
+            content_type = 0;
+            if (lws_hdr_copy(wsi, content_type_buf, sizeof(content_type_buf), WSI_TOKEN_HTTP_CONTENT_TYPE)>0 ){
+                printf( "+++++++++++++LWS_CALLBACK_HTTP_BODY_COMPLETION-----content_type:%s------------------\n", content_type_buf );
+                if(  strstr( content_type_buf, "multipart/form-data" ) ){
+                    content_type = 1; //upload
+                }else if(  strstr( content_type_buf, "application/json" ) ){
+                    content_type = 2; //json
+                }
+            }
+            if( content_type == 2 ){ //json
+
+                /* 构建 JSON 响应 */
+                if (pss->post_body) {
+                    char *resp = NULL;
+                    char *text1 = NULL;
+                    char *send = NULL;
+                    printf("接收到的JSON请求体: %s\n", pss->post_body);
+
+                    // 使用cJSON解析JSON格式的请求体
+                    if( process_http_post_message(pss->url, pss->post_body, pss->post_body_len, &resp) == 0){
+                        // 调试输出,查看解析后的参数
+                        printf( "process http post msg, resp[%s]\n", resp );
+
+
+                        char *json_body = resp;
+                        json_len = json_body ? strlen(json_body) : 0;
+
+                        /* 重置缓冲区指针用于HTTP头 */
+                        p = start;
+
+                        /* 设置 HTTP 头 */
+                        if (lws_add_http_common_headers(wsi, HTTP_STATUS_OK, "application/json",
+                                    json_len, &p, end) < 0) {
+                            printf("设置HTTP头失败\n");
+                            if (json_body) free(json_body);
+                            return -1;
+                        }
+                        if (lws_finalize_write_http_header(wsi, start, &p, end) < 0) {
+                            printf("写入HTTP头失败\n");
+                            if (json_body) free(json_body);
+                            return -1;
+                        }
+
+                        /* 写入 JSON 响应体 */
+                        if (lws_write(wsi, (unsigned char *)json_body, json_len, LWS_WRITE_HTTP_FINAL) < 0) {
+                            printf("写入响应体失败\n");
+                            if (json_body) free(json_body);
+                            return -1;
+                        }
+                        printf("成功返回JSON响应: %s\n", json_body);
+
+                        // 释放资源
+                        free(json_body);
+
+                    } else {
+                        /* JSON解析失败 */
+                        printf("JSON解析失败\n");
+                        // 使用cJSON构建错误响应
+                        cJSON *root = cJSON_CreateObject();
+                        if (root) {
+                            cJSON_AddStringToObject(root, "method", "POST");
+                            cJSON_AddStringToObject(root, "status", "error");
+                            cJSON_AddStringToObject(root, "message", "Invalid JSON format");
+
+                            json_response = cJSON_PrintUnformatted(root);
+                            json_len = json_response ? strlen(json_response) : 0;
+                        }
+
+                        if (lws_add_http_common_headers(wsi, HTTP_STATUS_BAD_REQUEST, "application/json",
+                                    json_len, &p, end) < 0) {
+                            if (root) cJSON_Delete(root);
+                            if (json_response) free((void*)json_response);
+                            return -1;
+                        }
+                        if (lws_finalize_write_http_header(wsi, start, &p, end) < 0) {
+                            if (root) cJSON_Delete(root);
+                            if (json_response) free((void*)json_response);
+                            return -1;
+                        }
+                        if (lws_write(wsi, (unsigned char *)json_response, json_len, LWS_WRITE_HTTP_FINAL) < 0) {
+                            if (root) cJSON_Delete(root);
+                            if (json_response) free((void*)json_response);
+                            return -1;
+                        }
+
+                        // 释放资源
+                        if (root) cJSON_Delete(root);
+                        if (json_response) free((void*)json_response);
+                    }
+                } else {
+                    /* 如果没有请求体,返回默认的JSON响应 */
+
+                    // 使用cJSON构建错误响应
+                    cJSON *root = cJSON_CreateObject();
+                    if (root) {
+                        cJSON_AddStringToObject(root, "method", "POST");
+                        cJSON_AddStringToObject(root, "status", "error");
+                        cJSON_AddStringToObject(root, "message", "No request body received");
+
+                        json_response = cJSON_PrintUnformatted(root);
+                        json_len = json_response ? strlen(json_response) : 0;
+                    }
+
+                    if (lws_add_http_common_headers(wsi, HTTP_STATUS_BAD_REQUEST, "application/json",
+                                json_len, &p, end) < 0) {
+                        if (root) cJSON_Delete(root);
+                        if (json_response) free((void*)json_response);
+                        return -1;
+                    }
+                    if (lws_finalize_write_http_header(wsi, start, &p, end) < 0) {
+                        if (root) cJSON_Delete(root);
+                        if (json_response) free((void*)json_response);
+                        return -1;
+                    }
+                    if (lws_write(wsi, (unsigned char *)json_response, json_len, LWS_WRITE_HTTP_FINAL) < 0) {
+                        if (root) cJSON_Delete(root);
+                        if (json_response) free((void*)json_response);
+                        return -1;
+                    }
+
+                    // 释放资源
+                    if (root) cJSON_Delete(root);
+                    if (json_response) free((void*)json_response);
+                }
+            }else if( content_type == 1 ){ //upload
+                lws_spa_finalize(pss->spa);
+
+
+                char *json_body = "{ \"code\":200, \"msg\":\"upload success\" }";
+                json_len = strlen(json_body);
+
+                /* 重置缓冲区指针用于HTTP头 */
+                p = start;
+
+                /* 设置 HTTP 头 */
+                if (lws_add_http_common_headers(wsi, HTTP_STATUS_OK, "application/json",
+                            json_len, &p, end) < 0) {
+                    printf("设置HTTP头失败\n");
+                    return -1;
+                }
+                if (lws_finalize_write_http_header(wsi, start, &p, end) < 0) {
+                    printf("写入HTTP头失败\n");
+                    return -1;
+                }
+
+                /* 写入 JSON 响应体 */
+                if (lws_write(wsi, (unsigned char *)json_body, json_len, LWS_WRITE_HTTP_FINAL) < 0) {
+                    printf("写入响应体失败\n");
+                    return -1;
+                }
+                printf("成功返回JSON响应: %s\n", json_body);
 
-                               // 释放资源
-                               if (root) cJSON_Delete(root);
-                               if (json_response) free((void*)json_response);
-                       }
+            }
                        break;
 
                case LWS_CALLBACK_HTTP_DROP_PROTOCOL:
index 6f9609e87e246190acdbec140f3d47eec3f3c557..2a6deaf2000f7614df27f8fdbb4a619d999cba4d 100644 (file)
             <h2>用户认证</h2>
             <div id="auth-status" class="auth-status logged-out">未登录</div>
             <span id="username-display" style="display: none;"></span>
-
-            <!-- 登录表单 -->
+<!-- 登录表单 -->
             <div id="login-form">
                 <div class="form-group">
                     <label for="username">用户名:</label>
-                    <input type="text" id="username" placeholder="输入用户名">
+                    <input type="text" id="username" value="admin" placeholder="输入用户名">
                 </div>
                 <div class="form-group">
                     <label for="password">密码:</label>
-                    <input type="password" id="password" placeholder="输入密码">
+                    <input type="password" id="password" value="password123" placeholder="输入密码">
                 </div>
                 <div class="button-group">
                     <button id="login-button" class="btn btn-primary">登录</button>
             <h2>GET请求测试</h2>
             <div class="form-group">
                 <label for="get-url">URL:</label>
-                <input type="text" id="get-url" value="http://192.168.1.1/api/version" placeholder="输入GET请求URL">
+                <input type="text" id="get-url" value="http://localhost:8000/api/get" placeholder="输入GET请求URL">
             </div>
             <div class="button-group">
                 <button id="get-request-button" class="btn">发送GET请求</button>
             <h2>WebSocket测试</h2>
             <div class="form-group">
                 <label for="websocket-url">WebSocket URL:</label>
-                <input type="text" id="websocket-url" value="ws://192.168.1.1/ws" placeholder="输入WebSocket URL">
+                <input type="text" id="websocket-url" value="ws://localhost:8000/ws/" placeholder="输入WebSocket URL">
             </div>
             <div class="button-group">
                 <button id="connect-websocket-button" class="btn btn-primary btn-disconnected">连接</button>
                 </div>
             </div>
         </div>
-    </div>
 
+        <!-- upload测试 -->
+               <p>
+        <div class="section">
+               <form id=myForm name=multipart action="/upload/" method="post" enctype="multipart/form-data">
+                       <h2>文件上传测试</h2>
+                       <input type="file" name="file" id="file" size="20">&nbsp;
+                               <span id=file_info style="font-size:12pt;"></span><br>
+                       <br>
+                       <input type="submit" name="send" value="Submit">
+               </form>
+        </div>
+    </div>
+<div id="responseMessage"></div>
     <script>
+       document.getElementById('myForm').addEventListener('submit', function(e) {
+              //处理上传文件成功后的响应处理,避免直接跳转到新页面
+
+            e.preventDefault(); // 阻止表单默认提交行为
+
+            const formData = new FormData(this);
+            const responseDiv = document.getElementById('responseMessage');
+
+            // 显示加载状态
+            responseDiv.innerHTML = '提交中...';
+            responseDiv.style.color = 'blue';
+
+            // 使用 Fetch API 发送请求
+            fetch('/upload/', {
+                method: 'POST',
+                body: formData
+            })
+            .then(response => {
+                if (!response.ok) {
+                    throw new Error('网络响应不正常');
+                }
+                return response.json(); // 假设服务器返回 JSON
+            })
+            .then(data => {
+                // 请求成功处理
+                responseDiv.innerHTML = `成功: ${data.message}`;
+                responseDiv.style.color = 'green';
+
+                // 可以在这里添加其他成功后的逻辑
+                console.log('服务器响应:', data);
+            })
+            .catch(error => {
+                // 错误处理
+                responseDiv.innerHTML = `错误: ${error.message}`;
+                responseDiv.style.color = 'red';
+                console.error('请求失败:', error);
+            });
+        });
+
         // WebSocket连接对象
         let webSocket = null;
         let heartbeatInterval = null;