cgi 上传文件(c 语言) 进度条显示
2015-01-10 23:44
134 查看
//虚拟机上搭建apache服务器上传文件
//1.代码:
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#include "dirent.h"
#include <wchar.h>
#include <assert.h>
static int atoii (char *zzzz)
{
int i = 0;
int num=0;
for(i=0;i<20;i++)
{
if(zzzz[i] >= '0' && zzzz[i] <= '9')
{
num = num * 10 + (zzzz[i] - '0');
}else
{
break;
}
}
return num;
}
char* getCgiData(FILE* fp, char* requestmethod)
{
char* input;
int len;
char *pppp;
int size = 1024;
int i = 0;
if(!strcmp(requestmethod, "GET"))
{
input = getenv("QUERY_STRING");
return input;
}
else if (!strcmp(requestmethod, "POST"))
{
pppp=getenv("CONTENT_LENGTH");
len = atoii(pppp);
input = (char*)malloc(sizeof(char)*(size + 1));
if (len == 0)
{
input[0] = '\0';
return input;
}
fgets(input, len+1, stdin);
input[len]='\0';
return input;
}
return NULL;
}
static unsigned int tmppp=0;
char *getFileName(unsigned char *req)
{
int i;
int leng;
tmppp=0;
char *psz1; char *psz2;
unsigned char *cur_post,*buf;
// get filename keyword
if ((psz1=strstr(req, "filename=")) == NULL)
{
return (char *)&tmppp;
}
// get pointer to actual filename (it's in quotes)
psz1+=strlen("filename=");
if ((psz1 = strtok(psz1, "\"")) == NULL)
{
return (char *)&tmppp;
}
// remove leading path for both PC and UNIX systems
if ((psz2 = strrchr(psz1,'\\')) != NULL)
{
psz1 = psz2+1;
}
if ((psz2 = strrchr(psz1,'/')) != NULL)
{
psz1 = psz2+1;
}
return psz1;
}
main()
{
char *reqMethod;
char *wp;
char *var=NULL;
int len;
long total,i,count;
char *fileName,*ps1,*ps2;
char *fileN;
char Boundary[256];
char errorBuf[200]="";
char tmpBuf[512];
char filePath[256]="/usr/local/apache2/webdav/";//directory of uploaded file
FILE *fileBuf=NULL;
reqMethod=getenv("REQUEST_METHOD");
len=atoii(getenv("CONTENT_LENGTH"));
printf("%s","Content-type:text/html \r\n\r\n");
//printf("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=UTF-8\"></head>");
Boundary[0] = '\r';
Boundary[1] = '\n';
Boundary[2] = '\0';
if (fgets(&Boundary[2], sizeof(Boundary)-2, stdin) == NULL)
{
sprintf(errorBuf,"%s","Get boundary failed !");
goto error;
}
//strip terminating CR / LF
if ((ps1=strchr(&Boundary[2],'\r')) != NULL)
{
*ps1 = '\0';
}
if ((ps1=strchr(&Boundary[2],'\n')) != NULL)
{
*ps1 = '\0';
}
//printf("Boundry=\"%s\"<br>",Boundary);
//printf("content-length=%d<br>",len);
fgets(tmpBuf,512,stdin);
//printf("All=%s<br>",tmpBuf);
fileName=getFileName(tmpBuf);
if(fileName)
{
//printf("fileName=%s<br>",fileName);
}
strcat(filePath,fileName);
//printf("filepath===%s<br>",filePath);
memset(tmpBuf,512,0x00);
fgets(tmpBuf,512,stdin);
//printf("%s<br>",tmpBuf);//content-type
memset(tmpBuf,512,0x00);
fgets(tmpBuf,512,stdin);
//printf("%s<br>",tmpBuf);// \r\n
if(fopen(filePath,"rb"))
{
sprintf(errorBuf,"%s","File already exist.");
goto error;
}
if ((fileBuf = fopen(filePath, "wb+")) == NULL)
{
sprintf(errorBuf,"%s","File open error.Make sure you have the permission.");
goto error;
}
// copy the file
while ((count=fread(tmpBuf, 1, 512, stdin)) != 0)
{
if ((fwrite(tmpBuf, 1, count, fileBuf)) != count)
{
sprintf(errorBuf,"%s","Write file error.");
goto error;
}
}
// re read last 128 bytes of file, handling files < 128 bytes
if ((count = ftell(fileBuf)) == -1)
{
goto error;
}
if (count > 128)
{
count = 128;
}
if (fseek(fileBuf, 0-count, SEEK_END) != 0)
{
goto error;
}
// get the new position
if ((total = ftell(fileBuf)) == -1)
{
goto error;
}
// and read the data from fileBuf
count = fread(tmpBuf, 1, sizeof(tmpBuf), fileBuf);
tmpBuf[count] = '\0';
//printf("count=%ld<br>",count);
// determine offset of terminating boundary line
for (i=0; i<=(count); i++)//-(long)strlen(Boundary)
{
//printf("%c",tmpBuf[i]);
if (tmpBuf[i] == Boundary[0])
{
//printf("found /r<br>");
if(strncmp(Boundary, &tmpBuf[i], strlen(Boundary)) == 0)
{
total+=i;
// printf("find boudary.<br>");
break;
}
}
}
//printf("<br>i=%ld<br>",i);
//printf("total=%ld<br>",total);
if (fseek(fileBuf,total, SEEK_SET) != 0)
{
goto error;
}
if ((total = ftell(fileBuf)) == -1)
{
goto error;
}
//printf("total=%ld<br>",total);
// truncate the terminating boundary line .
int fd=fileno(fileBuf);
ftruncate(fd,total);
fflush(fileBuf);
error:
if (fileBuf != NULL)
{
fclose(fileBuf);
}
if(errorBuf[0]!='\0')
//打印信息到网页的隐藏的iframe中
printf("<script type='text/javascript' language='javascript'>alert('%s');parent.location.replace('upload.html');</script>",errorBuf);
else
{//printf("file upload success !<br>");
printf("<script type='text/javascript' language='javascript'>alert('File upload success!');parent.location.replace('upload.html');</script>");
}
return;
}
2. 编译代码
gcc -o upload upload.c
3.网页文件,因无法通过ajax实现无刷新上传文件,只好借用隐藏的 iframe实现。包含有进度条哦!
[html] view
plaincopy
<html><head><title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<META http-equiv=Pragma content=no-cache>
<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
<script>
var time=0;
var delay_time=1000;
var loop_num=0;
function getRefToDivNest(divID, oDoc)
{
if( !oDoc ) { oDoc = document; }
if( document.layers ) {
if( oDoc.layers[divID] ) { return oDoc.layers[divID]; } else {
for( var x = 0, y; !y && x < oDoc.layers.length; x++ ) {
y = getRefToDivNest(divID,oDoc.layers[x].document); }
return y; } }
if( document.getElementById ) { return document.getElementById(divID); }
if( document.all ) { return document.all[divID]; }
return document[divID];
}
function progressBar( oBt, oBc, oBg, oBa, oWi, oHi, oDr )
{
MWJ_progBar++; this.id = 'MWJ_progBar' + MWJ_progBar; this.dir = oDr; this.width = oWi; this.height = oHi; this.amt = 0;
//write the bar as a layer in an ilayer in two tables giving the border
document.write( '<span id = "progress_div" class = "off" > <table border="0" cellspacing="0" cellpadding="'+oBt+'">'+
'<tr><td>Please wait...</td></tr><tr><td bgcolor="'+oBc+'">'+
'<table border="0" cellspacing="0" cellpadding="0"><tr><td height="'+oHi+'" width="'+oWi+'" bgcolor="'+oBg+'">' );
if( document.layers ) {
document.write( '<ilayer height="'+oHi+'" width="'+oWi+'"><layer bgcolor="'+oBa+'" name="MWJ_progBar'+MWJ_progBar+'"></layer></ilayer>' );
} else {
document.write( '<div style="position:relative;top:0px;left:0px;height:'+oHi+'px;width:'+oWi+';">'+
'<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>' );
}
document.write( '</td></tr></table></td></tr></table></span>\n' );
this.setBar = resetBar; //doing this inline causes unexpected bugs in early NS4
this.setCol = setColour;
}
function resetBar( a, b )
{
//work out the required size and use various methods to enforce it
this.amt = ( typeof( b ) == 'undefined' ) ? a : b ? ( this.amt + a ) : ( this.amt - a );
if( isNaN( this.amt ) ) { this.amt = 0; } if( this.amt > 1 ) { this.amt = 1; } if( this.amt < 0 ) { this.amt = 0; }
var theWidth = Math.round( this.width * ( ( this.dir % 2 ) ? this.amt : 1 ) );
var theHeight = Math.round( this.height * ( ( this.dir % 2 ) ? 1 : this.amt ) );
var theDiv = getRefToDivNest( this.id ); if( !theDiv ) { window.status = 'Progress: ' + Math.round( 100 * this.amt ) + '%'; return; }
if( theDiv.style ) { theDiv = theDiv.style; theDiv.clip = 'rect(0px '+theWidth+'px '+theHeight+'px 0px)'; }
var oPix = document.childNodes ? 'px' : 0;
theDiv.width = theWidth + oPix; theDiv.pixelWidth = theWidth; theDiv.height = theHeight + oPix; theDiv.pixelHeight = theHeight;
if( theDiv.resizeTo ) { theDiv.resizeTo( theWidth, theHeight ); }
theDiv.left = ( ( this.dir != 3 ) ? 0 : this.width - theWidth ) + oPix; theDiv.top = ( ( this.dir != 4 ) ? 0 : this.height - theHeight ) + oPix;
}
function setColour( a )
{
//change all the different colour styles
var theDiv = getRefToDivNest( this.id ); if( theDiv.style ) { theDiv = theDiv.style; }
theDiv.bgColor = a; theDiv.backgroundColor = a; theDiv.background = a;
}
function show_div(show,id) {
if(show){
document.getElementById(id).style.display = "block";
}else{
document.getElementById(id).style.display = "none";
}}
function progress()
{if (time < 1){time = time + 0.033;}
else {time = 0;
loop_num++;
}
setTimeout('progress()',delay_time);
myProgBar.setBar(time);
}
function sendClicked(F)
{ if(document.usb_upload.uploadedfile.value == ""){
document.usb_upload.uploadedfile.focus();
alert('File name can not be empty !');
return false;
}
F.submit();
show_div(true, "progress_div");
progress();}
function init(){show_div(0, "progress_div");}
</script>
</head>
<body onload=init();>
<h1>upload file</h1>
<form name="usb_upload" enctype="multipart/form-data" action="/cgi-bin/upload" method="post" target="hidden_frame"><p>
Select File:<input id="uploadedfile" type="file" size="35" name="uploadedfile">
<input id="Upload" onclick=sendClicked(this.form) type=button name="Upload" value="Upload"></p>
<iframe name='hidden_frame' id="hidden_frame" style='display:none'></iframe>
</form>
<iframe name='hidden_frame' id="hidden_frame" style='display:none'></iframe>
<script type="text/javascript" language="javascript1.2">
var MWJ_progBar = 0;
var myProgBar = new progressBar(1,'#2e2e2e', '#2e2e2e','#043db2',300,15,1);
</script><div id="current_directory" style="display:none"></div></body>
</html>
4.效果不错,上传几百兆文件无压力。
转载请注明出处/article/8916134.html
//1.代码:
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#include "dirent.h"
#include <wchar.h>
#include <assert.h>
static int atoii (char *zzzz)
{
int i = 0;
int num=0;
for(i=0;i<20;i++)
{
if(zzzz[i] >= '0' && zzzz[i] <= '9')
{
num = num * 10 + (zzzz[i] - '0');
}else
{
break;
}
}
return num;
}
char* getCgiData(FILE* fp, char* requestmethod)
{
char* input;
int len;
char *pppp;
int size = 1024;
int i = 0;
if(!strcmp(requestmethod, "GET"))
{
input = getenv("QUERY_STRING");
return input;
}
else if (!strcmp(requestmethod, "POST"))
{
pppp=getenv("CONTENT_LENGTH");
len = atoii(pppp);
input = (char*)malloc(sizeof(char)*(size + 1));
if (len == 0)
{
input[0] = '\0';
return input;
}
fgets(input, len+1, stdin);
input[len]='\0';
return input;
}
return NULL;
}
static unsigned int tmppp=0;
char *getFileName(unsigned char *req)
{
int i;
int leng;
tmppp=0;
char *psz1; char *psz2;
unsigned char *cur_post,*buf;
// get filename keyword
if ((psz1=strstr(req, "filename=")) == NULL)
{
return (char *)&tmppp;
}
// get pointer to actual filename (it's in quotes)
psz1+=strlen("filename=");
if ((psz1 = strtok(psz1, "\"")) == NULL)
{
return (char *)&tmppp;
}
// remove leading path for both PC and UNIX systems
if ((psz2 = strrchr(psz1,'\\')) != NULL)
{
psz1 = psz2+1;
}
if ((psz2 = strrchr(psz1,'/')) != NULL)
{
psz1 = psz2+1;
}
return psz1;
}
main()
{
char *reqMethod;
char *wp;
char *var=NULL;
int len;
long total,i,count;
char *fileName,*ps1,*ps2;
char *fileN;
char Boundary[256];
char errorBuf[200]="";
char tmpBuf[512];
char filePath[256]="/usr/local/apache2/webdav/";//directory of uploaded file
FILE *fileBuf=NULL;
reqMethod=getenv("REQUEST_METHOD");
len=atoii(getenv("CONTENT_LENGTH"));
printf("%s","Content-type:text/html \r\n\r\n");
//printf("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=UTF-8\"></head>");
Boundary[0] = '\r';
Boundary[1] = '\n';
Boundary[2] = '\0';
if (fgets(&Boundary[2], sizeof(Boundary)-2, stdin) == NULL)
{
sprintf(errorBuf,"%s","Get boundary failed !");
goto error;
}
//strip terminating CR / LF
if ((ps1=strchr(&Boundary[2],'\r')) != NULL)
{
*ps1 = '\0';
}
if ((ps1=strchr(&Boundary[2],'\n')) != NULL)
{
*ps1 = '\0';
}
//printf("Boundry=\"%s\"<br>",Boundary);
//printf("content-length=%d<br>",len);
fgets(tmpBuf,512,stdin);
//printf("All=%s<br>",tmpBuf);
fileName=getFileName(tmpBuf);
if(fileName)
{
//printf("fileName=%s<br>",fileName);
}
strcat(filePath,fileName);
//printf("filepath===%s<br>",filePath);
memset(tmpBuf,512,0x00);
fgets(tmpBuf,512,stdin);
//printf("%s<br>",tmpBuf);//content-type
memset(tmpBuf,512,0x00);
fgets(tmpBuf,512,stdin);
//printf("%s<br>",tmpBuf);// \r\n
if(fopen(filePath,"rb"))
{
sprintf(errorBuf,"%s","File already exist.");
goto error;
}
if ((fileBuf = fopen(filePath, "wb+")) == NULL)
{
sprintf(errorBuf,"%s","File open error.Make sure you have the permission.");
goto error;
}
// copy the file
while ((count=fread(tmpBuf, 1, 512, stdin)) != 0)
{
if ((fwrite(tmpBuf, 1, count, fileBuf)) != count)
{
sprintf(errorBuf,"%s","Write file error.");
goto error;
}
}
// re read last 128 bytes of file, handling files < 128 bytes
if ((count = ftell(fileBuf)) == -1)
{
goto error;
}
if (count > 128)
{
count = 128;
}
if (fseek(fileBuf, 0-count, SEEK_END) != 0)
{
goto error;
}
// get the new position
if ((total = ftell(fileBuf)) == -1)
{
goto error;
}
// and read the data from fileBuf
count = fread(tmpBuf, 1, sizeof(tmpBuf), fileBuf);
tmpBuf[count] = '\0';
//printf("count=%ld<br>",count);
// determine offset of terminating boundary line
for (i=0; i<=(count); i++)//-(long)strlen(Boundary)
{
//printf("%c",tmpBuf[i]);
if (tmpBuf[i] == Boundary[0])
{
//printf("found /r<br>");
if(strncmp(Boundary, &tmpBuf[i], strlen(Boundary)) == 0)
{
total+=i;
// printf("find boudary.<br>");
break;
}
}
}
//printf("<br>i=%ld<br>",i);
//printf("total=%ld<br>",total);
if (fseek(fileBuf,total, SEEK_SET) != 0)
{
goto error;
}
if ((total = ftell(fileBuf)) == -1)
{
goto error;
}
//printf("total=%ld<br>",total);
// truncate the terminating boundary line .
int fd=fileno(fileBuf);
ftruncate(fd,total);
fflush(fileBuf);
error:
if (fileBuf != NULL)
{
fclose(fileBuf);
}
if(errorBuf[0]!='\0')
//打印信息到网页的隐藏的iframe中
printf("<script type='text/javascript' language='javascript'>alert('%s');parent.location.replace('upload.html');</script>",errorBuf);
else
{//printf("file upload success !<br>");
printf("<script type='text/javascript' language='javascript'>alert('File upload success!');parent.location.replace('upload.html');</script>");
}
return;
}
2. 编译代码
gcc -o upload upload.c
3.网页文件,因无法通过ajax实现无刷新上传文件,只好借用隐藏的 iframe实现。包含有进度条哦!
[html] view
plaincopy
<html><head><title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<META http-equiv=Pragma content=no-cache>
<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
<script>
var time=0;
var delay_time=1000;
var loop_num=0;
function getRefToDivNest(divID, oDoc)
{
if( !oDoc ) { oDoc = document; }
if( document.layers ) {
if( oDoc.layers[divID] ) { return oDoc.layers[divID]; } else {
for( var x = 0, y; !y && x < oDoc.layers.length; x++ ) {
y = getRefToDivNest(divID,oDoc.layers[x].document); }
return y; } }
if( document.getElementById ) { return document.getElementById(divID); }
if( document.all ) { return document.all[divID]; }
return document[divID];
}
function progressBar( oBt, oBc, oBg, oBa, oWi, oHi, oDr )
{
MWJ_progBar++; this.id = 'MWJ_progBar' + MWJ_progBar; this.dir = oDr; this.width = oWi; this.height = oHi; this.amt = 0;
//write the bar as a layer in an ilayer in two tables giving the border
document.write( '<span id = "progress_div" class = "off" > <table border="0" cellspacing="0" cellpadding="'+oBt+'">'+
'<tr><td>Please wait...</td></tr><tr><td bgcolor="'+oBc+'">'+
'<table border="0" cellspacing="0" cellpadding="0"><tr><td height="'+oHi+'" width="'+oWi+'" bgcolor="'+oBg+'">' );
if( document.layers ) {
document.write( '<ilayer height="'+oHi+'" width="'+oWi+'"><layer bgcolor="'+oBa+'" name="MWJ_progBar'+MWJ_progBar+'"></layer></ilayer>' );
} else {
document.write( '<div style="position:relative;top:0px;left:0px;height:'+oHi+'px;width:'+oWi+';">'+
'<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>' );
}
document.write( '</td></tr></table></td></tr></table></span>\n' );
this.setBar = resetBar; //doing this inline causes unexpected bugs in early NS4
this.setCol = setColour;
}
function resetBar( a, b )
{
//work out the required size and use various methods to enforce it
this.amt = ( typeof( b ) == 'undefined' ) ? a : b ? ( this.amt + a ) : ( this.amt - a );
if( isNaN( this.amt ) ) { this.amt = 0; } if( this.amt > 1 ) { this.amt = 1; } if( this.amt < 0 ) { this.amt = 0; }
var theWidth = Math.round( this.width * ( ( this.dir % 2 ) ? this.amt : 1 ) );
var theHeight = Math.round( this.height * ( ( this.dir % 2 ) ? 1 : this.amt ) );
var theDiv = getRefToDivNest( this.id ); if( !theDiv ) { window.status = 'Progress: ' + Math.round( 100 * this.amt ) + '%'; return; }
if( theDiv.style ) { theDiv = theDiv.style; theDiv.clip = 'rect(0px '+theWidth+'px '+theHeight+'px 0px)'; }
var oPix = document.childNodes ? 'px' : 0;
theDiv.width = theWidth + oPix; theDiv.pixelWidth = theWidth; theDiv.height = theHeight + oPix; theDiv.pixelHeight = theHeight;
if( theDiv.resizeTo ) { theDiv.resizeTo( theWidth, theHeight ); }
theDiv.left = ( ( this.dir != 3 ) ? 0 : this.width - theWidth ) + oPix; theDiv.top = ( ( this.dir != 4 ) ? 0 : this.height - theHeight ) + oPix;
}
function setColour( a )
{
//change all the different colour styles
var theDiv = getRefToDivNest( this.id ); if( theDiv.style ) { theDiv = theDiv.style; }
theDiv.bgColor = a; theDiv.backgroundColor = a; theDiv.background = a;
}
function show_div(show,id) {
if(show){
document.getElementById(id).style.display = "block";
}else{
document.getElementById(id).style.display = "none";
}}
function progress()
{if (time < 1){time = time + 0.033;}
else {time = 0;
loop_num++;
}
setTimeout('progress()',delay_time);
myProgBar.setBar(time);
}
function sendClicked(F)
{ if(document.usb_upload.uploadedfile.value == ""){
document.usb_upload.uploadedfile.focus();
alert('File name can not be empty !');
return false;
}
F.submit();
show_div(true, "progress_div");
progress();}
function init(){show_div(0, "progress_div");}
</script>
</head>
<body onload=init();>
<h1>upload file</h1>
<form name="usb_upload" enctype="multipart/form-data" action="/cgi-bin/upload" method="post" target="hidden_frame"><p>
Select File:<input id="uploadedfile" type="file" size="35" name="uploadedfile">
<input id="Upload" onclick=sendClicked(this.form) type=button name="Upload" value="Upload"></p>
<iframe name='hidden_frame' id="hidden_frame" style='display:none'></iframe>
</form>
<iframe name='hidden_frame' id="hidden_frame" style='display:none'></iframe>
<script type="text/javascript" language="javascript1.2">
var MWJ_progBar = 0;
var myProgBar = new progressBar(1,'#2e2e2e', '#2e2e2e','#043db2',300,15,1);
</script><div id="current_directory" style="display:none"></div></body>
</html>
4.效果不错,上传几百兆文件无压力。
转载请注明出处/article/8916134.html
相关文章推荐
- cgi 上传文件(c 语言) 进度条显示
- cgi 上传文件(c 语言) 进度条显示
- 大文件上传 进度条显示 (仿csdn资源上传效果)
- Ajax--上传进度条显示文件的状态。
- Jquery和BigFileUpload实现大文件上传及进度条显示
- Extjs 使用fileupload插件上传文件 带进度条显示
- 基于uploadify.js实现多文件上传和上传进度条的显示
- Meteor用CollectionsFS上传文件时进度条的显示
- Ajax上传文件进度条显示
- Struts2+JQuery.uploadify插件实现带进度的多文件上传示例【也可以设置去掉进度条的显示】
- Jquery和BigFileUpload实现大文件上传及进度条显示
- 大文件上传 进度条显示 (仿csdn资源上传效果)
- js+php实现文件上传显示文件上传进度条的插件
- 大文件上传 进度条显示(仿CSDN资源上传效果) .
- ajaxSubmit() 上传文件和进度条显示
- Ajax + Servlet 实现上传文件进度条显示
- 大文件上传 进度条显示(仿CSDN资源上传效果)
- Asp.Net 无刷新文件上传并显示进度条的实现方法及思路
- 大文件上传 进度条显示(仿CSDN资源上传效果)
- SpringMVC之文件上传(进度条显示)