Reputation: 166
I have created a cgi file in c. I have an html file in which the user can select the file he/she wants to upload.
The problem is that when I select the file, the value of the file is just the name of the file and not the directory so I cannot read the file.
How should I access the file?
<form action="./cgi-bin/paperload.cgi" method="get">
<pre>Title: <input type="text" name="title"><br></pre>
<pre>Author: <input type="text" name="author"><br></pre>
<pre>File: <input type="file" name="file"><br></pre>
<pre><input type="submit" value="Upload paper"></pre>
</form>
c - cgi code
void getParam(const char *Name, char Value[256]) {
char *pos1 = strstr(data, Name);
if (pos1) {
pos1 += strlen(Name);
if (*pos1 == '=') { // Make sure there is an '=' where we expect it
pos1++;
while (*pos1 && *pos1 != '&') {
if (*pos1 == '%') { // Convert it to a single ASCII character and store at our Valueination
*Value++ = (char)ToHex(pos1[1]) * 16 + ToHex(pos1[2]);
pos1 += 3;
} else if( *pos1=='+' ) { // If it's a '+', store a space at our Valueination
*Value++ = ' ';
pos1++;
} else {
*Value++ = *pos1++; // Otherwise, just store the character at our Valueination
}
}
*Value++ = '\0';
return;
}
}
strcpy(Value, "undefine"); // If param not found, then use default parameter
return;
}
main code
// check for a correct id
data = getenv("QUERY_STRING");
getParam("title",paper->author_name);
getParam("author",paper->paper_title);
getParam("file",paper->paper_file_name);
paper_file = fopen(paper->paper_file_name, "r+");
if (paper_file) {
// we continue to read until we reach end of file
while(!feof(paper_file)){
fread(paper->paper_content,BUFSIZ, 1, paper_file);
}
//close the file
fclose(paper_file);
}
else {
fprintf(stderr, "Unable to open file %s", paper->paper_file_name);
exit(-1);
}
Even If i use POST method the problem still exists. The issue is not how to parse the input from html. The problem is when I try to fread in the main code.
If I change the type in html from file to text and try to give the path of the file manually, how should be the syntax?
Upvotes: 0
Views: 990
Reputation: 161
You don't need the directory information, the file content is attached to the POST request and you need to grab it from there. I suggest you use cgic and qdecoder as CGI libraries that take care of the process for you. Or you can at least understand how they are parsing the request headers and maybe apply the same logic in your own application.
Qdecoder Upload file example: http://www.qdecoder.org/releases/current/examples/uploadfile.c
Upvotes: 1