我使用libmicrohttpd创建http服务器,并使用html文件创建响应。这是创建响应的函数,该函数取决于用户名,我要显示不同类型的文件。
static int answer_to_connection (void *cls, struct MHD_Connection `
*connection,const char *url, const char *method,const char *version, const char
*upload_data,size_t *upload_data_size, void **con_cls){
char *user=NULL;
char *pass=NULL;
int fail=false;
int ret;
struct MHD_Response *response;
struct MHD_Response *risimg;
if (0 != strcmp (method, "GET")){return MHD_NO;}
if (NULL == *con_cls){*con_cls = connection;return MHD_YES;}
if (user != NULL) free (user);if (pass != NULL) free (pass);
user = MHD_basic_auth_get_username_password (connection, &pass);
const char*possibili[]={"Root","Pietro","Matteo","Giovanni","Michela"};
FILE * file;
int fd[2];
FILE* img;
struct stat sbuf;
struct stat bruf;
if(user==NULL){fail=true;}
else{
for (int i =0 ;i<5;++i){if(strcmp(user,possibili[i]))break;else if(i==4) fail=true;}
if(strcmp(user,possibili[0])and !strcmp(pass,"execu7e97XC++"))fail=true;}
if (fail){
const char *page = "<html><body>Go away.</body></html>";
response =MHD_create_response_from_buffer (strlen (page), (void *)
page,MHD_RESPMEM_PERSISTENT);
ret = MHD_queue_basic_auth_fail_response (connection,"myrealm",response);}
else {//char* posizione;
char* totale;
//asprintf(&posizione,"%s%s","/home/bomps/Scrivania/ok/",user);
asprintf(&totale,"%s%s",user,".html");
if ( stat (totale,&sbuf)!=0 ){const char *errorstr ="<html><body>An
internal server error has occured!</body></html>";
response =MHD_create_response_from_buffer (strlen(errorstr),
(void*)errorstr,MHD_RESPMEM_PERSISTENT);
ret = MHD_queue_response (connection, MHD_HTTP_NOT_FOUND, response);}
else {
fd[0]=open(totale,O_RDONLY);
//file = fopen (totale,"rb");response = MHD_create_response_from_callback
(sbuf.st_size, 32 * 1024, /* 32k page size
*/&file_reader,file,&free_callback);
response=MHD_create_response_from_fd(sbuf.st_size,fd[0]);
//img=fopen("background-hd-vintage-2.jpg","rb");
fd[1]=open("background-hd-vintage-2.jpg",O_RDONLY);
stat ("background-hd-vintage-2.jpg",&bruf);
//risimg=MHD_create_response_from_fd(bruf.st_size,fd[1]);
//MHD_queue_response (connection, MHD_HTTP_OK, risimg);
//MHD_add_response_header (risimg, "Data-Type", "background-hd-vintage-
2/jpg");
ret = MHD_queue_response (connection, MHD_HTTP_OK, response);};}
if (user != NULL) free (user);if (pass != NULL) free
(pass);MHD_destroy_response (response);return ret;}
这样创建的响应已发送,我能够在服务器中看到它,但是有错误。在我写的html代码的一行中
background-image: url("background-hd-vintage-2.jpg");
我在html文件的同一目录中,该目录也是服务器程序的目录。问题是,如果我在服务器中打开文件html,则不会显示该图像,并且如果我查看页面analisis,则表明该图像为localhost:8888 / background-hd-vintage-2.jpg。 我试图将URL更改为“ file:///home/bomps/Scrivania/tutto_insieme/background-hd-vintage-2.jpg”,但是它不起作用。 所以我可以通过服务器传递文件以便我的javascript找到它吗?或者失败了,如何让我的程序找到文件?
提前感谢大家的答复