cgic上傳文件
『壹』 使用CGIC如何實現Web文件上傳大神們幫幫忙
用C語言編寫cgi程序的話,CGIC是非常流行的庫,官方頁面及下載地址為: www.boutell.com/cgic/#obtain 不少網站都有文件上傳的功能,本文展示如何用CGIC庫編寫文件上傳的服務端程序,最後給出一段簡單的HTML代碼,供大家測試使用。//upload.c#include #include #include #include #include #include"cgic.h"#define BufferLen 1024int 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程序所在目錄下創建新文件。