开发者

how in C++ send file to browser

开发者 https://www.devze.com 2023-01-24 12:58 出处:网络
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:

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) {
       开发者_JS百科     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);
}


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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消