S
S
s2sk2018-05-20 02:18:07
C++ / C#
s2sk, 2018-05-20 02:18:07

How to send an image to the browser?

Hello.

I can't figure out what I'm doing wrong. I want to send a picture to the browser, and the browser gives me "the file is corrupted". Here's the code:

std::ifstream filePNG("image.png");
        
        filePNG.seekg(0, std::ios_base::end);
        long size = filePNG.tellg();
        filePNG.seekg(0, std::ios::beg);

        char* data = new char[size];	
        filePNG.read(data, size);

        response << "HTTP/1.1 200 OK\r\n"
          << "Version: HTTP/1.1\r\n"
          << "Content-Type: image/png\r\n"
          << "Content-Length: " << size
          << "\r\n\r\n"
          << data;

        printf("img send");

send(client_socket, response.str().c_str(),
        response.str().length(), 0);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Yudakov, 2018-05-20
@s2sk

The picture should not be attempted to be converted to a string. Nothing good will come of this idea.
First we send the headers - as a string. And then the picture - as an array of bytes.
PS The Version header is redundant.

M
Mercury13, 2018-05-20
@Mercury13

1. Both streams open in binary mode.
2. The << operation will send our PNG as ASCIIZ - that is, it will stop writing when a null character is encountered. And it is necessary in its entirety, with the write command.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question