Linux_CGI_CGIC - 文件上传

用C语言库(CGIC)编写CGI,实现文件上传

本文展示如何用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");
    //获取文件名
    if(cgiFormFileName("file",name,sizeof(name))!=cgiFormSuccess){
        fprintf(stderr,"could not retrieve filename/n");    
        goto FAIL;
    }
    //获取文件大小
    cgiFormFileSize("file",&size);
    //获取文件类型
    cgiFormFileContentType("file",contentType,sizeof(contentType));
    //打开Form文件
    if(cgiFormFileOpen("file",&file))
    {
        fprintf(stderr,"could not open the file/n");    
        goto FAIL;}
    t=-1;
    //获取去除路径的文件名
    while(1){
        tmpStr = strstr(name+t+1,"//"); 
        if(NULL!=tmpStr)
            t=(int)(tmpStr-name);
        else break;


    }
    strcpy(fileNameOnServer,name+t+1);
    mode = S_IRWXU|S_IRGRP|S_IROTH;
    //打开本地文件(用作拷贝Form文件)
    targetFile = open(fileNameOnServer,O_RDWR|O_CREAT|O_TRUNC|O_APPEND,mode);
    if(targetFile<0){
    fprintf(stderr,"could not creat 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");
END:
    printf("File %s has been uploaded",fileNameOnServer);
    return 0;
}

编译方法与之前相同
测试用HTML代码:

   <html>
       <head>
               <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
                   <title>Test Upload</title>
                   <meta name="author" content="Jack">
       </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>
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值