cgi 上传文件(c 语言) 进度条显示


[cpp]
  view plain copy
  1. //虚拟机上搭建apache服务器上传文件  
  2. //1.代码:  
  3. #include "stdio.h"  
  4. #include "string.h"  
  5. #include "stdlib.h"  
  6. #include "dirent.h"  
  7. #include <wchar.h>  
  8. #include <assert.h>  
  9. static int atoii (char *zzzz)  
  10. {  
  11.   int i = 0;  
  12.   int num=0;  
  13. for(i=0;i<20;i++)  
  14. {  
  15.   if(zzzz[i] >= '0' && zzzz[i] <= '9')  
  16.     {  
  17.       num = num * 10 + (zzzz[i] - '0');  
  18.     }else  
  19.     {  
  20.             break;  
  21.     }  
  22. }  
  23.   return num;  
  24. }  
  25.   
  26.   
  27. char* getCgiData(FILE* fp, char* requestmethod)  
  28. {  
  29.   
  30.        char* input;  
  31.        int len;  
  32.        char *pppp;  
  33.        int size = 1024;  
  34.        int i = 0;  
  35.      if(!strcmp(requestmethod, "GET"))  
  36.        {  
  37.   
  38.               input = getenv("QUERY_STRING");  
  39.               return input;  
  40.   
  41.        }  
  42.        else if (!strcmp(requestmethod, "POST"))  
  43.        {  
  44.             pppp=getenv("CONTENT_LENGTH");  
  45.              len = atoii(pppp);  
  46.               input = (char*)malloc(sizeof(char)*(size + 1));      
  47.   
  48.               if (len == 0)  
  49.               {  
  50.                      input[0] = '\0';  
  51.   
  52.                      return input;  
  53.               }  
  54.           
  55.         fgets(input, len+1, stdin);  
  56.             input[len]='\0';  
  57.          return input;  
  58.        }  
  59.   
  60.        return NULL;  
  61. }  
  62.   
  63. static unsigned int tmppp=0;  
  64.   
  65. char *getFileName(unsigned char *req)  
  66. {  
  67.     int i;  
  68.     int leng;  
  69.     tmppp=0;  
  70.     char *psz1; char *psz2;  
  71.     unsigned char *cur_post,*buf;  
  72.   
  73.     // get filename keyword  
  74.     if ((psz1=strstr(req, "filename=")) == NULL)  
  75.     {  
  76.     return (char *)&tmppp;  
  77.     }  
  78.   
  79.     // get pointer to actual filename (it's in quotes)  
  80.     psz1+=strlen("filename=");  
  81.     if ((psz1 = strtok(psz1, "\"")) == NULL)  
  82.     {  
  83.     return (char *)&tmppp;  
  84.     }  
  85.     // remove leading path for both PC and UNIX systems  
  86.     if ((psz2 = strrchr(psz1,'\\')) != NULL)  
  87.     {  
  88.     psz1 = psz2+1;  
  89.     }  
  90.     if ((psz2 = strrchr(psz1,'/')) != NULL)  
  91.     {  
  92.     psz1 = psz2+1;  
  93.     }  
  94.     return psz1;  
  95. }  
  96.   
  97.   
  98. main()  
  99. {  
  100.     char *reqMethod;  
  101.     char *wp;  
  102.     char *var=NULL;  
  103.     int len;  
  104.     long total,i,count;  
  105.     char *fileName,*ps1,*ps2;  
  106.     char *fileN;  
  107.     char Boundary[256];  
  108.     char errorBuf[200]="";  
  109.     char tmpBuf[512];  
  110.     char filePath[256]="/usr/local/apache2/webdav/";//directory of uploaded file  
  111.     FILE *fileBuf=NULL;  
  112.     reqMethod=getenv("REQUEST_METHOD");  
  113.     len=atoii(getenv("CONTENT_LENGTH"));  
  114.     printf("%s","Content-type:text/html \r\n\r\n");  
  115.     //printf("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=UTF-8\"></head>");  
  116.   
  117.     Boundary[0] = '\r';  
  118.     Boundary[1] = '\n';  
  119.     Boundary[2] = '\0';  
  120.   
  121.     if (fgets(&Boundary[2], sizeof(Boundary)-2, stdin) == NULL)  
  122.     {  
  123.         sprintf(errorBuf,"%s","Get boundary failed !");  
  124.         goto error;  
  125.     }  
  126.   
  127.     //strip terminating CR / LF  
  128.     if ((ps1=strchr(&Boundary[2],'\r')) != NULL)  
  129.     {  
  130.         *ps1 = '\0';  
  131.     }  
  132.   
  133.     if ((ps1=strchr(&Boundary[2],'\n')) != NULL)  
  134.     {  
  135.         *ps1 = '\0';  
  136.     }  
  137.     //printf("Boundry=\"%s\"<br>",Boundary);  
  138.   
  139.     //printf("content-length=%d<br>",len);  
  140.     fgets(tmpBuf,512,stdin);  
  141.     //printf("All=%s<br>",tmpBuf);  
  142.     fileName=getFileName(tmpBuf);  
  143.   
  144.     if(fileName)  
  145.     {  
  146.         //printf("fileName=%s<br>",fileName);  
  147.     }  
  148.     strcat(filePath,fileName);    
  149.     //printf("filepath===%s<br>",filePath);  
  150.   
  151.     memset(tmpBuf,512,0x00);  
  152.     fgets(tmpBuf,512,stdin);  
  153.     //printf("%s<br>",tmpBuf);//content-type  
  154.     memset(tmpBuf,512,0x00);  
  155.     fgets(tmpBuf,512,stdin);      
  156.     //printf("%s<br>",tmpBuf);// \r\n  
  157.   
  158.     if(fopen(filePath,"rb"))  
  159.     {  
  160.         sprintf(errorBuf,"%s","File already exist.");  
  161.         goto error;  
  162.     }  
  163.   
  164.     if ((fileBuf = fopen(filePath, "wb+")) == NULL)  
  165.     {  
  166.         sprintf(errorBuf,"%s","File open error.Make sure you have the permission.");  
  167.         goto error;  
  168.     }  
  169.     // copy the file  
  170.     while ((count=fread(tmpBuf, 1, 512, stdin)) != 0)  
  171.     {  
  172.         if ((fwrite(tmpBuf, 1, count, fileBuf)) != count)  
  173.         {  
  174.             sprintf(errorBuf,"%s","Write file error.");  
  175.             goto error;  
  176.         }  
  177.     }  
  178.     // re read last 128 bytes of file, handling files < 128 bytes  
  179.     if ((count = ftell(fileBuf)) == -1)  
  180.     {  
  181.         goto error;  
  182.     }  
  183.   
  184.     if (count > 128)  
  185.     {  
  186.         count = 128;  
  187.     }  
  188.   
  189.     if (fseek(fileBuf, 0-count, SEEK_END) != 0)  
  190.     {  
  191.         goto error;  
  192.     }  
  193.     // get the new position  
  194.     if ((total = ftell(fileBuf)) == -1)  
  195.     {  
  196.         goto error;  
  197.     }  
  198.   
  199.     // and read the data from fileBuf  
  200.     count = fread(tmpBuf, 1, sizeof(tmpBuf), fileBuf);  
  201.     tmpBuf[count] = '\0';  
  202.     //printf("count=%ld<br>",count);  
  203.     // determine offset of terminating boundary line  
  204.     for (i=0; i<=(count); i++)//-(long)strlen(Boundary)  
  205.     {  
  206.         //printf("%c",tmpBuf[i]);  
  207.         if (tmpBuf[i] == Boundary[0])  
  208.         {  
  209.             //printf("found /r<br>");  
  210.             if(strncmp(Boundary, &tmpBuf[i], strlen(Boundary)) == 0)  
  211.             {  
  212.             total+=i;  
  213.         //  printf("find boudary.<br>");  
  214.             break;  
  215.             }  
  216.         }  
  217.     }  
  218.     //printf("<br>i=%ld<br>",i);  
  219.     //printf("total=%ld<br>",total);  
  220.     if (fseek(fileBuf,total, SEEK_SET) != 0)  
  221.     {  
  222.         goto error;  
  223.     }  
  224.   
  225.     if ((total = ftell(fileBuf)) == -1)  
  226.     {  
  227.     goto error;  
  228.     }  
  229.     //printf("total=%ld<br>",total);  
  230.     // truncate the terminating boundary line .  
  231.     int fd=fileno(fileBuf);  
  232.     ftruncate(fd,total);  
  233.   
  234.     fflush(fileBuf);  
  235. error:  
  236.     if (fileBuf != NULL)  
  237.     {  
  238.         fclose(fileBuf);  
  239.     }  
  240.     if(errorBuf[0]!='\0')  
  241.         //打印信息到网页的隐藏的iframe中  
  242.     printf("<script type='text/javascript' language='javascript'>alert('%s');parent.location.replace('upload.html');</script>",errorBuf);  
  243.     else   
  244.     {//printf("file upload success !<br>");  
  245.     printf("<script type='text/javascript' language='javascript'>alert('File upload success!');parent.location.replace('upload.html');</script>");    
  246.     }  
  247.     return;  
  248.       
  249. }  


 

2. 编译代码

 gcc -o upload upload.c

3.网页文件,因无法通过ajax实现无刷新上传文件,只好借用隐藏的 iframe实现。包含有进度条哦!

[html]  view plain copy
  1. <html><head><title></title>  
  2.   
  3. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  4.   
  5. <META http-equiv=Pragma content=no-cache>  
  6.   
  7. <META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">  
  8.   
  9.   
  10. <script>  
  11.   
  12. var time=0;  
  13.   
  14. var delay_time=1000;  
  15.   
  16. var loop_num=0;  
  17.   
  18. function getRefToDivNest(divID, oDoc)   
  19.   
  20. {  
  21.   
  22.   if( !oDoc ) { oDoc = document; }  
  23.   
  24.   if( document.layers ) {  
  25.   
  26.     if( oDoc.layers[divID] ) { return oDoc.layers[divID]; } else {  
  27.   
  28.     for( var x = 0, y; !y && x < oDoc.layers.length; x++ ) {  
  29.   
  30.         y = getRefToDivNest(divID,oDoc.layers[x].document); }  
  31.   
  32.     return y; } }  
  33.   
  34.   if( document.getElementById ) { return document.getElementById(divID); }  
  35.   
  36.   if( document.all ) { return document.all[divID]; }  
  37.   
  38.   return document[divID];  
  39.   
  40. }  
  41.   
  42. function progressBar( oBt, oBc, oBg, oBa, oWi, oHi, oDr )   
  43.   
  44. {  
  45.   
  46.   MWJ_progBar++; this.id = 'MWJ_progBar' + MWJ_progBar; this.dir = oDrthis.width = oWithis.height = oHithis.amt = 0;  
  47.   
  48.   //write the bar as a layer in an ilayer in two tables giving the border  
  49.   
  50.   document.write( '<span id = "progress_div" class = "off" > <table border="0" cellspacing="0" cellpadding="'+oBt+'">'+  
  51.   
  52.     '<tr><td>Please wait...</td></tr><tr><td bgcolor="'+oBc+'">'+  
  53.   
  54.         '<table border="0" cellspacing="0" cellpadding="0"><tr><td height="'+oHi+'" width="'+oWi+'" bgcolor="'+oBg+'">' );  
  55.   
  56.   if( document.layers ) {  
  57.   
  58.     document.write( '<ilayer height="'+oHi+'" width="'+oWi+'"><layer bgcolor="'+oBa+'" name="MWJ_progBar'+MWJ_progBar+'"></layer></ilayer>' );  
  59.   
  60.   } else {  
  61.   
  62.     document.write( '<div style="position:relative;top:0px;left:0px;height:'+oHi+'px;width:'+oWi+';">'+  
  63.   
  64.             '<div style="position:absolute;top:0px;left:0px;height:0px;width:0;font-size:1px;background-color:'+oBa+';" id="MWJ_progBar'+MWJ_progBar+'"></div></div>' );  
  65.   
  66.   }  
  67.   
  68.   document.write( '</td></tr></table></td></tr></table></span>\n' );  
  69.   
  70.   this.setBar = resetBar; //doing this inline causes unexpected bugs in early NS4  
  71.   
  72.   this.setCol = setColour;  
  73.   
  74. }  
  75.   
  76.   
  77.   
  78. function resetBar( a, b )   
  79.   
  80. {  
  81.   
  82.   //work out the required size and use various methods to enforce it  
  83.   
  84.   this.amt = ( typeof( b ) == 'undefined' ) ? a : b ? ( this.amt + a ) : ( this.amt - a );  
  85.   
  86.   if( isNaN( this.amt ) ) { this.amt = 0; } if( this.amt > 1 ) { this.amt = 1; } if( this.amt < 0 ) { this.amt = 0; }  
  87.   
  88.   var theWidth = Math.round( this.width * ( ( this.dir % 2 ) ? this.amt : 1 ) );  
  89.   
  90.   var theHeight = Math.round( this.height * ( ( this.dir % 2 ) ? 1 : this.amt ) );  
  91.   
  92.   var theDiv = getRefToDivNest( this.id ); if( !theDiv ) { window.status = 'Progress: ' + Math.round( 100 * this.amt ) + '%'; return; }  
  93.   
  94.   if( theDiv.style ) { theDiv = theDiv.style; theDiv.clip = 'rect(0px '+theWidth+'px '+theHeight+'px 0px)'; }  
  95.   
  96.   var oPix = document.childNodes ? 'px' : 0;  
  97.   
  98.   theDiv.width = theWidth + oPix; theDiv.pixelWidth = theWidththeDiv.height = theHeight + oPix; theDiv.pixelHeight = theHeight;  
  99.   
  100.   if( theDiv.resizeTo ) { theDiv.resizeTo( theWidth, theHeight ); }  
  101.   
  102.   theDiv.left = ( ( this.dir != 3 ) ? 0 : this.width - theWidth ) + oPix; theDiv.top = ( ( this.dir != 4 ) ? 0 : this.height - theHeight ) + oPix;  
  103.   
  104. }  
  105.   
  106.   
  107.   
  108. function setColour( a )   
  109.   
  110. {  
  111.   
  112.   //change all the different colour styles  
  113.   
  114.   var theDiv = getRefToDivNest( this.id ); if( theDiv.style ) { theDiv = theDiv.style; }  
  115.   
  116.   theDiv.bgColor = atheDiv.backgroundColor = atheDiv.background = a;  
  117.   
  118. }  
  119.   
  120. function show_div(show,id) {  
  121.   
  122. if(show){  
  123.   
  124. document.getElementById(id).style.display  = "block";  
  125.   
  126. }else{  
  127.   
  128. document.getElementById(id).style.display  = "none";  
  129.   
  130. }}  
  131.   
  132. function progress()  
  133.   
  134. {if (time < 1){time = time + 0.033;}  
  135.   
  136. else {time = 0;  
  137.   
  138. loop_num++;  
  139.   
  140. }  
  141.   
  142. setTimeout('progress()',delay_time);  
  143.   
  144. myProgBar.setBar(time);  
  145.   
  146. }  
  147. function sendClicked(F)  
  148.   
  149. { if(document.usb_upload.uploadedfile.value == ""){  
  150.   
  151. document.usb_upload.uploadedfile.focus();  
  152.   
  153. alert('File name can not be empty !');  
  154.   
  155. return false;  
  156.   
  157. }  
  158.   
  159. F.submit();  
  160.   
  161. show_div(true, "progress_div");  
  162.   
  163. progress();}  
  164.   
  165. function init(){show_div(0, "progress_div");}  
  166.   
  167. </script>  
  168.   
  169. </head>  
  170.   
  171. <body onload=init();>  
  172.   
  173. <h1>upload file</h1>  
  174.   
  175.   
  176. <form name="usb_upload" enctype="multipart/form-data" action="/cgi-bin/upload" method="post" target="hidden_frame"><p>  
  177.   
  178. Select File:<input id="uploadedfile" type="file" size="35" name="uploadedfile">    
  179.   
  180. <input id="Upload" onclick=sendClicked(this.form) type=button name="Upload" value="Upload"></p>  
  181.   
  182. <iframe name='hidden_frame' id="hidden_frame" style='display:none'></iframe>   
  183.   
  184. </form>  
  185. <iframe name='hidden_frame' id="hidden_frame" style='display:none'></iframe>  
  186. <script type="text/javascript" language="javascript1.2">  
  187.   
  188. var MWJ_progBar = 0;  
  189.   
  190. var myProgBar = new progressBar(1,'#2e2e2e', '#2e2e2e','#043db2',300,15,1);  
  191.   
  192. </script><div id="current_directory" style="display:none"></div></body>  
  193. </html>  
  194.    

 4.效果不错,上传几百兆文件无压力。
转载请注明出处http://blog.csdn.net/fengchao_2009/article/details/7699292

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值