美文网首页
2021-11-12 使用cgic 文件上传测试

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

作者: eversay | 来源:发表于2021-11-12 01:28 被阅读0次
#include <stdio.h>
#include "cgic.h"
#include <string.h>
#include <stdlib.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

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("<p>No file was uploaded.<p>\n");
        return;
    } 
    fprintf(cgiOut, "The filename submitted was: ");

    /*处理操作系统或者由于浏览器引起的上传的文件的绝对路径 引起的上传后的名字问题*/
    //correct the name of file
    correctedName = correctName(name);

    cgiHtmlEscape(correctedName);

    fprintf(cgiOut, "<p>\n");
    cgiFormFileSize("file", &size);
    fprintf(cgiOut, "The file size was: %.2f k<p>\n", (size*1.0)/1024);
    cgiFormFileContentType("file", contentType, sizeof(contentType));
    fprintf(cgiOut, "The alleged content type of the file was: ");
    cgiHtmlEscape(contentType);
    fprintf(cgiOut, "<p>\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.<p>\n");
    if (cgiFormFileOpen("file", &file) != cgiFormSuccess) {
        fprintf(cgiOut, "Could not open the file.<p>\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, "<pre>\n");
    while (cgiFormFileRead(file, buffer, sizeof(buffer), &got) ==
        cgiFormSuccess)
    {
        write(fd, buffer, got);
    //  cgiHtmlEscapeData(buffer, got);//display the buffer
    }
    fprintf(cgiOut, "</pre>\n");
    close(fd);
    cgiFormFileClose(file);
    return 0;
}

相关文章

网友评论

      本文标题:2021-11-12 使用cgic 文件上传测试

      本文链接:https://www.haomeiwen.com/subject/kejnzltx.html