How to send file with http using C ++

I want to write server side code. It should work with popular browsers and wget. My server checks this file for presence or not, if it exists, the browser can download it. But I have some problems. Honestly, I read a lot of questions and answers (for example: Send a binary in an HTTP response using C-sockets ), but I did not recognize. My browser (Chrome) can receive text. But I can not send binary data or images, etc. I am changing the header according to the file upload. But I can not send downloads.

I have some questions.

void *clientWorker(void * acceptSocket) {
     int newSocket = (int) acceptSocket;
     char okStatus[] = "HTTP/1.1 200 OK\r\n"
                       "Content-Type: text/html\r\n"
                       "Connection: close\r\n"
                       "Content-Length: 20\r\n"
                       "\r\n"
                       "s";
     writeLn(newSocket, okStatus);
     const char * fileName = "/home/tyra/Desktop/example.txt";
     sendF(newSocket, fileName);
}

1 - If I did not write "s" or something else in okStatus, my message cannot be sent. I don’t understand anything about this.

writeLn:

void writeLn(int acceptSocket, const char * buffer) {
    int n = write(acceptSocket, buffer, strlen(buffer) - 1);
    if (n < 0) {
        error("Error while writing");
    }
}

sendF:

string buffer;
string line;
ifstream myfile(fileName);
struct stat filestatus;
stat(fileName, &filestatus);
int fsize = filestatus.st_size;
if (myfile.is_open()) {
    while (myfile.good()) {
        getline(myfile, line);
        buffer.append(line);
    }
    cout << buffer << endl;
}
writeLn(acceptSocket, buffer.c_str());
cout << fsize << " bytes\n";

. . , .

2 - , , . (123\n456\n789), (123456789). , Content-Type, .

, . . ?

, .

+3
3

, "Content-Length: xxxx\r\n". , , , .

, writeF std::string :

string buffer;

. char :

int fsize = file.tellg();
char* buffer = new char[fsize];
file.seekg (0, ios::beg);
file.read (buffer, size);
file.close();

, HTML, Content-Type: text/plain; <br> "\ r\n".

, ( ),

Content-Type: application/octet-stream
+2

strlen. strlen , '\ 0'. "\ 0".

. int n = write(acceptSocket, buffer, strlen(buffer) - 1); strlen

writeLn(acceptSocket, buffer.c_str()); writeLn(acceptSocket, buffer.c_str(), buffer.size()); ...

123\n456\n789 <PRE>123\n456\n789</PRE>, html . , , - \n <BR>...

+1

Regarding question 1 - if you do not want to send any content back, delete sfrom the end okStatusand indicate Content-Length: 0\r\nin the header

0
source

All Articles