1.文件上传
该功能通过使用cgic来实现。
(1)界面代码
(2)执行函数代码
enum ErrLog
{
ErrSucceed,
ErrOpenFile,
ErrNoFile
};
enum ErrLog UploadFile()
{
cgiFilePtr file;
FILE *fd;
char name[512];
char path[128];
char contentType[1024];
int size = 0;
int got = 0;
int t = 0;
char *tmp = NULL;
if (cgiFormFileName("uploadfile", name, sizeof(name)) != cgiFormSuccess) //获取客户端pathname
{
printf(" No file was uploaded.
\n");
return ErrNoFile;
}
fprintf(cgiOut, "The filename submitted was: ");
cgiHtmlEscape(name);
fprintf(cgiOut, "
\n");
cgiFormFileSize("uploadfile", &size);
fprintf(cgiOut, "The file size was: %d bytes
\n", size);
cgiFormFileContentType("uploadfile", contentType, sizeof(contentType));
fprintf(cgiOut, "The alleged content type of the file was: ");
cgiHtmlEscape(contentType);
fprintf(cgiOut, "
\n");
if (cgiFormFileOpen("uploadfile", &file) != cgiFormSuccess) //尝试打开上传的,并存放在系统中的临时文件
{
fprintf(cgiOut, " Could not open the file.
\n");
return ErrOpenFile;
}
t = -1;
while (1)
{
tmp = strstr(name+t+1, "\\"); // 从pathname解析出filename
if (NULL == tmp)
{
tmp = strstr(name+t+1, "/");
}
if (NULL != tmp)
{
t = (int)(tmp-name);
}
else
{
break;
}
}
tmp = (char *)malloc(size * sizeof(char)); // 在底层建立新文件
strcpy(path, "/usr/local/boa/data/");
strcat(path, name+t+1);
fd = fopen(path, "w+");
if (fd == NULL)
{
return ErrOpenFile;
}
while (cgiFormFileRead(file, tmp, size, &got) == cgiFormSuccess) // 从临时文件读出content
{
fwrite(tmp, size, sizeof(char), fd); //把读出的content写入新文件
}
fprintf(cgiOut, " Upload File Success.
\n");
cgiFormFileClose(file);
free(tmp);
fclose(fd);
return ErrSucceed;
}
2.文件下载
(1)借助HTML中a标签实现,如:download="filename"> download ,则打开浏览器点击链接即可实现文件下载。
注:其中download属性可避免直接打开文件,进而执行下载任务;该方式的优点是在静态html界面即可实现文件下载,缺点是暴露了文件及其路径。
界面代码
xx设置
xx模块
(2)当然,上述操作借助了部分浏览器内嵌的功能,而对于另一部分浏览器来说必须通过后台代码来实现文件的读、写和存,间接实现文件的下载,该部分可参考《嵌入式Linux下基于CGI的文件上传下载的实现》。
执行代码
void download(char *filename)
{
FIFE *fp;
char buff[SIZE];
struct stat s;
time_t date;
int n;
date = time(NULL);
stat(filename, &s);
printf(“Content Disposition:filename=\“%s\” date=%s\n”, filename, ctime(&date));
printf(“Content Length:size==%d\n”, s.st_size);
if (fp = fopen(filename, “r”))
{
while ((n = fread(buff, sizeof(char), sizeof(buff), fp)) > 0)
{
fwrite(buff, n, 1, stdout)
}
fclose(fp);
}
}