我将一个 HTML 表单放入 C 语言的 CGI 文件中,并使用如下 fprintf 语句:
<form action="cgi-bin/upload.cgi" method="post" enctype="multipart/form-data">
<p>Photo to Upload: <input type="file" name="photo" /></p>
<p>Your Email Address: <input type="text" name="email_address" /></p>
<p><input type="submit" name="Submit" value="Submit Form" /></p>
</form>
我想知道是否可以获取文件输入(从具有多部分/表单数据正文的表单请求的值),将其转换为 C 代码(通过获取 url 数据处理值),然后上传从那里归档?顺便说一句,我不允许使用 PHP,因为我目前使用的机器空间非常有限。
最佳答案
此示例不使用任何非标准库:
#include <stdio.h>
#include <stdlib.h>
#define MAXLEN 80
#define EXTRA 5
/* 4 for field name "data", 1 for "=" */
#define MAXINPUT MAXLEN + EXTRA + 2
/* 1 for added line break, 1 for trailing NUL */
#define DATAFILE "../data/data.txt"
void unencode(char * src, char * last, char * dest) {
for (; src != last; src++, dest++)
if ( * src == '+')
* dest = ' ';
else if ( * src == '%') {
int code;
if (sscanf(src + 1, "%2x", & code) != 1) code = '?'; * dest = code;
src += 2;
} else
*dest = * src; * dest = '\n'; * ++dest = '\0';
}
int main(void) {
char * lenstr;
char input[MAXINPUT], data[MAXINPUT];
long len;
printf("%s%c%c\n",
"Content-Type:text/html;charset=iso-8859-1", 13, 10);
printf("<TITLE>Response</TITLE>\n");
lenstr = getenv("CONTENT_LENGTH");
if (lenstr == NULL || sscanf(lenstr, "%ld", & len) != 1 || len > MAXLEN)
printf("<P>Error in invocation - wrong FORM probably.");
else {
FILE * f;
fgets(input, len + 1, stdin);
unencode(input + EXTRA, input + len, data);
f = fopen(DATAFILE, "a");
if (f == NULL)
printf("<P>Sorry, cannot store your data.");
else
fputs(data, f);
fclose(f);
printf("<P>Thank you! The following contribution of yours has \
been stored:<BR>%s", data);
}
return 0;
}
关于html - 在 C 中使用 CGI 将 HTML 表单数据文件上传到服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45027419/