Liutas
Liutas

Reputation: 5783

how in C++ send file to browser

I need to send file from my directory to user. The problem file was not send. Can any one help me?

My code is like:

CHttpServerContext* pCtxt;
// ... there i set headers for open

    DWORD dwRead;
    CString fileName = "c:\txt.doc";

    HANDLE hFile = CreateFile (fileName, GENERIC_READ, FILE_SHARE_READ, 
      (LPSECURITY_ATTRIBUTES) NULL, 
      OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, (HANDLE) NULL);
   if (hFile == INVALID_HANDLE_VALUE)
   {
      return;
   }


   int c = 0;
   CHAR szBuffer [2048];
   do
    {
        if (c++ > 20) {
            break;
            return;
        }
        // read chunk of the file
        if (!ReadFile (hFile, szBuffer, 2048, &dwRead, NULL))
        {
         return;
        }
        if (!dwRead)
         // EOF reached, bail out
         break;

        // Send binary chunk to the browser
        if (!pCtxt->WriteClient( szBuffer, &dwRead, 0))
        {
         return;
        }
    }
    while (1);
    CloseHandle (hFile);
}

Upvotes: 0

Views: 503

Answers (2)

JBRWilkinson
JBRWilkinson

Reputation: 4865

No point in re-inventing the wheel - just use the TransmitFile API instead - it is built into CHttpServerContent::TransmitFile().

Upvotes: 0

valdo
valdo

Reputation: 12943

Doctor, I'm sick. What's wrong with me?

I mean, you give almost no information about what happened.

  1. Do you know if some function returned you an error in your code?
  2. Why do you abort the loop after 20 iterations? This limits you to 40KB.
  3. How exactly do you initialize CHttpServerContext?
  4. You might use high-performance TransmitFile function if you just send the file as-is.
  5. What is your client? How do you know it didn't get the file?

Upvotes: 3

Related Questions