2021-11-12 使用cgic 文件上传测试

#include 
#include "cgic.h"
#include 
#include 

#include 
#include 
#include 
#include 

char *correctName(char *p)
{
    char *delimPos = NULL;

    delimPos = strtok(p, "\\");

    while(NULL != (delimPos = strtok(NULL, "\\"))){
        p = delimPos;
    }
    return p;
}

int cgiMain() 
{
    cgiFilePtr file;
    char name[1024];
    char contentType[1024];
    char buffer[1024];
    int size;
    int got;
    char nameOnServer[1024]="/home/book/project/uploads/";
    char *correctedName = NULL;
    /*原以为与操作系统有关,后来查了相关资料 才知道是 浏览器的安全权限 ie的太低,会显示绝对路径,其他的不会*/
    int fd;

    cgiHeaderContentType("text/html");
    if (cgiFormFileName("file", name, sizeof(name)) != cgiFormSuccess) {
        printf("

No file was uploaded.

\n"); return; } fprintf(cgiOut, "The filename submitted was: "); /*处理操作系统或者由于浏览器引起的上传的文件的绝对路径 引起的上传后的名字问题*/ //correct the name of file correctedName = correctName(name); cgiHtmlEscape(correctedName); fprintf(cgiOut, "

\n"); cgiFormFileSize("file", &size); fprintf(cgiOut, "The file size was: %.2f k

\n", (size*1.0)/1024); cgiFormFileContentType("file", contentType, sizeof(contentType)); fprintf(cgiOut, "The alleged content type of the file was: "); cgiHtmlEscape(contentType); fprintf(cgiOut, "

\n"); fprintf(cgiOut, "Of course, this is only the claim the browser made when uploading the file. Much like the filename, it cannot be trusted.

\n"); if (cgiFormFileOpen("file", &file) != cgiFormSuccess) { fprintf(cgiOut, "Could not open the file.

\n"); return; } strcat(nameOnServer, correctedName); if((fd = open(nameOnServer, O_RDWR|O_CREAT|O_APPEND))<0){ fprintf(cgiOut, "could not creat the new file on the server,%s\n", nameOnServer); return; } fprintf(cgiOut, "

\n");
    while (cgiFormFileRead(file, buffer, sizeof(buffer), &got) ==
        cgiFormSuccess)
    {
        write(fd, buffer, got);
    //  cgiHtmlEscapeData(buffer, got);//display the buffer
    }
    fprintf(cgiOut, "
\n"); close(fd); cgiFormFileClose(file); return 0; }

你可能感兴趣的:(2021-11-12 使用cgic 文件上传测试)