如何使用FastCGI C/C 应用程序访问POST请求的主体

how to access a body of POST request using fastcgi C/C++ application

本文关键字:请求 POST 主体 访问 应用程序 何使用 FastCGI      更新时间:2023-10-16

我正在使用http://fastcgi.com/在C 应用程序中使用库作为后端,而Nginx Web-Server作为前端。

成功地从HTML形式发布文件,可以在Nginx服务器端看到临时文件。但是我不知道如何使用fastcgi_stdio访问多部分邮政请求的主体。这是我的html形式。

<html>
    <head>
        <title>Test Server</title>
        <script src="http://code.jquery.com/jquery.min.js"></script>
    </head>
    <body>
        <form id="upload-form" method="post" target="upload_target"   enctype="multipart/form-data" action="/upload">
            <input name="file" id="file" size="27" type="file" /><br />
            <input type="submit" name="action" value="Upload" /><br />
            <iframe id="upload_target" name="upload_target" src="" style="width:100%;height:100px;border:0px solid #fff;"></iframe>
        </form>
    </body>
</html>

我的nginx conf文件:

location /upload {
# Pass altered request body to this location
upload_pass @test;
# Store files to this directory
# The directory is hashed, subdirectories 0 1 2 3 4 5 6 7 8 9 should exist
upload_store /www/test;
# Allow uploaded files to be read only by user
upload_store_access user:rw group:r all:r;
# Set specified fields in request body
upload_set_form_field $upload_field_name.name $upload_file_name;
upload_set_form_field $upload_field_name.content_type "$upload_content_type";
upload_set_form_field $upload_field_name.path "$upload_tmp_path";
# Inform backend about hash and size of a file
upload_aggregate_form_field "$upload_field_name.md5" "$upload_file_md5";
upload_aggregate_form_field "$upload_field_name.size" "$upload_file_size";
upload_pass_form_field "^submit$|^description$";
upload_cleanup 400 404 499 500-505;
}
include fastcgi.conf;
# Pass altered request body to a backend
location @test {
        fastcgi_pass  localhost:8080
}

现在,如何在我的fastcgi C 应用程序中处理/获取POST请求主体,以及如何在Fastcgi应用程序端的适当文件中写入它?

是否有更好的快速模块可以实现这一目标?

谢谢。

您可以通过FCGI_stdin流访问POST主体。例如,您可以使用FCGI_getchar一次从中读取一个字节,这是FCGI_fgetc(FCGI_stdin)的简短表格。您可以使用FCGI_fread在单个调用中读取较大的数据。我发现所有这些都在看源。这些来源通常会引用所谓的" H&amp; s"的内容 - 这代表" Harbison and Steele",《书C:参考手册》的作者,这些数字是指该书的章节和部分。

,顺便说一句,它称为"标准输入/输出"的" stdio"。不是"工作室"。这些功能的行为应像同行一样,没有FCGI_前缀。因此,有关详细信息,请查看getcharfread等的人页。

在应用程序中包含字节后,您可以使用普通的STDIO操作或通过FCGI_fopen打开的文件将其写入文件。但是请注意,输入流将不会直接对应上传文件的内容。相反,MIME编码用于传输所有表单数据,包括文件。如果要访问文件数据,则必须分析该流。

使用以下:

char * method = getenv("REQUEST_METHOD");
if (!strcmp(method, "POST")) {
    int ilen = atoi(getenv("CONTENT_LENGTH"));
    char *bufp = malloc(ilen);
    fread(bufp, ilen, 1, stdin);
    printf("The POST data is<P>%sn", bufp);
    free(bufp);
}