使用CGIC实现Web文件上传的服务端代码

本文介绍如何使用CGIC库实现C语言CGI程序的文件上传功能,包括处理文件大小限制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转至:http://www.blogjava.net/tmpbuf/archive/2008/11/20/141501.html

用C语言编写cgi程序的话,CGIC是非常流行的库,官方页面及下载地址为:www.boutell.com/cgic/#obtain
      不少网站都有文件上传的功能,本文展示如何用CGIC库编写文件上传的服务端程序,最后给出一段简单的HTML代码,供大家测试使用。

//upload.c
#include<stdio.h>
#include< string.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/stat.h>
#include"cgic.h"
#define BufferLen 1024
int cgiMain( void){
    cgiFilePtr file;
     int    targetFile;
    mode_t    mode;
     char name[128];
     char fileNameOnServer[64];
     char contentType[1024];
     char buffer[BufferLen];
     char *tmpStr=NULL;
     int size;
     int got,t;
    cgiHeaderContentType("text/html");
     // 取得html页面中file元素的值,应该是文件在客户机上的路径名
     if (cgiFormFileName("file", name,  sizeof(name)) !=cgiFormSuccess) {
        fprintf(stderr,"could not retrieve filename\n");
         goto FAIL;
    } 
    cgiFormFileSize("file", &size);
     // 取得文件类型,不过本例中并未使用
    cgiFormFileContentType("file", contentType,  sizeof(contentType));
     // 目前文件存在于系统临时文件夹中,通常为/tmp,通过该命令打开临时文件。临时文件的名字与用户文件的名字不同,所以不能通过路径/tmp/userfilename的方式获得文件
     if (cgiFormFileOpen("file", &file) != cgiFormSuccess) {
        fprintf(stderr,"could not open the file\n");
         goto FAIL;
    }
    t=-1;
     // 从路径名解析出用户文件名
     while(1){
        tmpStr=strstr(name+t+1,"\\");
         if(NULL==tmpStr)
            tmpStr=strstr(name+t+1,"/"); // if "\\" is not path separator, try "/"
         if(NULL!=tmpStr)
            t=( int)(tmpStr-name);
         else
             break;
    }
    strcpy(fileNameOnServer,name+t+1);
    mode=S_IRWXU|S_IRGRP|S_IROTH;    
     // 在当前目录下建立新的文件,第一个参数实际上是路径名,此处的含义是在cgi程序所在的目录(当前目录))建立新文件    
    targetFile=open(fileNameOnServer,O_RDWR|O_CREAT|O_TRUNC|O_APPEND,mode);
     if(targetFile<0){
        fprintf(stderr,"could not create the new file,%s\n",fileNameOnServer);
         goto    FAIL;
    }
     // 从系统临时文件中读出文件内容,并放到刚创建的目标文件中
     while (cgiFormFileRead(file, buffer, BufferLen, &got) ==cgiFormSuccess){
         if(got>0)
            write(targetFile,buffer,got);    
    }
    cgiFormFileClose(file);
    close(targetFile);
     goto    END;
FAIL:
    fprintf(stderr,"Failed to upload");
     return 1;
END:    
    printf("File \"%s\" has been uploaded",fileNameOnServer);
     return 0;
}
      假设该文件存储为upload.c,则使用如下命令编辑:
gcc -Wall upload.c cgic.c -o upload.cgi
      编译完成后把upload.cgi复制到你部署cgi程序的目录(通常命名为cgi-bin)。
      正式部署时,请务必修改用open创建新文件那一行代码。把open的第一个参数设置为目标文件在服务器上存储的绝对路径,或者相对于cgi程序的相对路径。本例中,出于简单考虑,在cgi程序所在目录下创建新文件。


      测试用HTML代码: upload.html
<! DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd"
>
< html >
< head >
     < meta  http-equiv ="Content-Type"  content ="text/html; charset=utf-8" >
     < title >Test Upload </ title >
     < meta  name ="author"  content ="Jack" >
     <!--  Date: 2007-08-30  -->
</ head >
< body >
< form  action ="cgi-bin/upload.cgi"  method ="post"  enctype ="multipart/form-data"  target ="_blank" >
     < input  type ="file"  name ="file"  value =""   />
     < input  type ="submit"  name ="submit"  value ="OK" >
</ form >
</ body >
</ html >
      最后的文件目录结构为
      /MyWebRoot
      |---/upload.html
      |---/cgi-bin
      |------/upload.cgi

      当然,你必须配置能够cgi-bin,并且程序要有权限在cgi-bin目录下创建文件(因为此例把文件上传到cgi-bin目录下)。


      那么如何控制上传文件的大小呢?因为你有时会不允许用户上传太大的文件。
      通过分析cgic.c的源代码,我们发现它定义了一个变量cgiContentLength,表示请求的长度。但我们需要首先判断这是一个上传文件的请求,然后才能根据cgiContentLength来检查用户是否要上传一个太大的文件。
      cgic.c的main函数中进行了一系列if-else判断来检查请求的类型,首先确定这是一个post请求,然后确定数据的编码方式为 "multipart/form-data",这个判断通过之后,就要开始准备接收数据了。所以我们要在接收数据开始之前使用 cgiContentLength判断大小,如果超过标准,就立即返回,不允许继续操作。
      下面贴出修改后代码片段(直接修改cgic.c的源代码即可):
else  if (cgiStrEqNc(cgiContentType, "multipart/form-data")) {
#ifdef CGICDEBUG
            CGICDEBUGSTART
            fprintf(dout, "Calling PostMultipartInput\n");
            CGICDEBUGEND    
#endif /* CGICDEBUG */
             // 我的代码
            
// UpSize:文件长度上限值,以byte为单位,UpSize是一个int变量,因为cgiContentLength的类型为int
             if(cgiContentLength>UpSize){ 
                cgiHeaderContentType("text/html");
                printf("File too large!\n");
                cgiFreeResources();
                 return -1;
            }
             // 我的代码结束
             if (cgiParsePostMultipartInput() != cgiParseSuccess) {
#ifdef CGICDEBUG
                CGICDEBUGSTART
                fprintf(dout, "PostMultipartInput failed\n");
                CGICDEBUGEND    
#endif /* CGICDEBUG */
                cgiFreeResources();
                 return -1;
            }    
#ifdef CGICDEBUG
            CGICDEBUGSTART
            fprintf(dout, "PostMultipartInput succeeded\n");
            CGICDEBUGEND    
#endif /* CGICDEBUG */
        }
    }
      变量UpSize表示文件大小的上限。在cgic.c的main中找到相关代码,并修改成上面这样即可。你可以在cgic.c中定义UpSize,也可以在刚才完成的upload.c中定义,然后在cgic.c中用extern方式引用。

support my English blog:  http://www.phacai.com/how-to-implement-file-upload-with-cgic



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值