用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>