【问题标题】:File is downloaded but content is missing文件已下载但内容缺失
【发布时间】:2013-01-02 09:32:49
【问题描述】:

我正在使用 WCF 上传和下载文件。我正在使用以下内容进行下载。

try
        {
            MyService.IWITSService clientDownload = new WITSServiceClient();
            MyService.DownloadRequest requestData = new DownloadRequest();
            MyService.RemoteFileInfo fileInfo = new RemoteFileInfo();
            requestData.ItemID = Convert.ToInt32(Request.QueryString["id"]);

            fileInfo = clientDownload.DownloadFile(requestData);

            Response.BufferOutput = false;   // to prevent buffering 
            byte[] buffer = new byte[6500000];
            int bytesRead = 0;

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.ContentType = fileInfo.FileExt;
            HttpContext.Current.Response.AddHeader("Content-Disposition","attachment; filename=" + fileInfo.FileName);

            bytesRead = fileInfo.FileByteStream.Read(buffer, 0, buffer.Length);

            while (bytesRead > 0)
            {
                // Verify that the client is connected.
                if (Response.IsClientConnected)
                {

                    Response.OutputStream.Write(buffer, 0, bytesRead);
                    // Flush the data to the HTML output.
                    Response.Flush();

                    buffer = new byte[6500000];
                    bytesRead = fileInfo.FileByteStream.Read(buffer, 0, buffer.Length);

                }
                else
                {
                    bytesRead = -1;
                }
            }
        }
        catch (Exception ex)
        {
            // Trap the error, if any.
            System.Web.HttpContext.Current.Response.Write("Error : " + ex.Message);
        }
        finally
        {
            Response.Flush();
            Response.Close();
            Response.End();
            System.Web.HttpContext.Current.Response.Close();
        }

文件已下载,但文件数据不显示。文件大小与实际相同 尺寸。任何人都可以帮助我在我必须改变的地方.. 提前谢谢..

【问题讨论】:

  • 您是否在调试器中单步执行此代码以验证是否正在从服务器读取数据?
  • 是的..从服务器读取数据..
  • 你上传的是什么类型的文件?
  • .docx 文件,或任何其他文件...
  • 您检查是否满足所有要求的条件?

标签: c# asp.net wcf web-applications web-config


【解决方案1】:

您既不想打电话给Response.Close(),也不想打电话给System.Web.HttpContext.Current.Response.Close()。它会中断与客户端的连接。

HttpResponse.Close Method 的文档说:

此方法突然终止与客户端的连接 方式并且不适用于正常的 HTTP 请求处理。这 方法向客户端发送一个重置数据包,这可能会导致响应 缓存在服务器、客户端或其他地方的数据 之间被丢弃。

您可能会使用此方法来响应恶意 HTTP 的攻击 客户。但是,通常您应该调用 CompleteRequest,如果 您想跳转到 EndRequest 事件并发送响应到 客户。

因此将finally 代码简化为:

finally
{
    Response.Flush();
    Response.End();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-27
    • 2017-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-09
    相关资源
    最近更新 更多