//虚拟机上搭建apache服务器上传文件
//1.代码:
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#include "dirent.h"
#include
#include
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("
http-equiv=\"Content-Type\"
content=\"text/html;charset=UTF-8\">");
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\"
",Boundary);
//printf("content-length=%d
",len);
fgets(tmpBuf,512,stdin);
//printf("All=%s
",tmpBuf);
fileName=getFileName(tmpBuf);
if(fileName)
{
//printf("fileName=%s
",fileName);
}
strcat(filePath,fileName);
//printf("filepath===%s
",filePath);
memset(tmpBuf,512,0x00);
fgets(tmpBuf,512,stdin);
//printf("%s
",tmpBuf);//content-type
memset(tmpBuf,512,0x00);
fgets(tmpBuf,512,stdin);
//printf("%s
",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
",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
");
if(strncmp(Boundary, &tmpBuf[i], strlen(Boundary))
== 0)
{
total+=i;
// printf("find
boudary.
");
break;
}
}
}
//printf("
i=%ld
",i);
//printf("total=%ld
",total);
if (fseek(fileBuf,total,
SEEK_SET) != 0)
{
goto error;
}
if ((total =
ftell(fileBuf)) == -1)
{
goto error;
}
//printf("total=%ld
",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("",errorBuf);
else
{//printf("file upload
success !
");
printf("
success!');parent.location.replace('upload.html');");
}
return;
}
2. 编译代码
gcc -o upload upload.c
3.网页文件,因无法通过ajax实现无刷新上传文件,只好借用隐藏的
iframe实现。包含有进度条哦!
[html] view plaincopy
?
content="text/html; charset=UTF-8">
content=no-cache>
CONTENT="NO-CACHE">
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.getElementByIdx ) { return
document.getElementByIdx(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( '
"progress_div" class = "off" >
border="0" cellspacing="0" cellpadding="'+oBt+'">'+
'
Pleasewait...
bgcolor="'+oBc+'">'+
'
cellspacing="0"
cellpadding="0">
height="'+oHi+'" width="'+oWi+'" bgcolor="'+oBg+'">'
);
if( document.layers ) {
document.write(
'
width="'+oWi+'">
bgcolor="'+oBa+'"
name="MWJ_progBar'+MWJ_progBar+'">
');
} else {
document.write(
'
style="position:relative;top:0px;left:0px;height:'+oHi+'px;width:'+oWi+';">'+
'
style="position:absolute;top:0px;left:0px;height:0px;width:0;font-size:1px;background-color:'+oBa+';"
id="MWJ_progBar'+MWJ_progBar+'">
);
}
document.write(
'
\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.getElementByIdx(id).style.display =
"block";
}else{
document.getElementByIdx(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");}
file
enctype="multipart/form-data" action="/cgi-bin/upload"
method="post"
target="hidden_frame">
Select File:
type="file" size="35" name="uploadedfile">
οnclick=sendClicked(this.form) type=button name="Upload"
value="Upload">
style='display:none'>
style='display:none'>
var MWJ_progBar = 0;
var myProgBar = new progressBar(1,'#2e2e2e',
'#2e2e2e','#043db2',300,15,1);
id="current_directory"
style="display:none">
4.效果不错,上传几百兆文件无压力。
转载请注明出处http://blog.csdn.net/fengchao_2009/article/details/7699292