0

我有下面的代码,它适用于小文件,但对于大文件,它会根据需要生成 zip,但不会下载它。我得到了各种各样的错误,包括超时(我已经设法解决了)。另一个问题是它在同步中运行。我自己生成的最大文件是一个 330MB 的 zip 文件,其中附有大约 30 张高清图像。但这甚至可以达到 GB,因为用户可以选择一次下载大约 100 个甚至更多的高清图像。

为了解决这两个问题,我认为下载async可能对这两种情况都有帮助。我想提醒用户他们的下载已经开始,并且他们会在下载准备好时收到通知。

我正在考虑在客户端发送流IsConnected(然后删除文件)或发送电子邮件以要求他们在决定注销时下载文件(然后使用离线下载链接删除文件)。我只是不知道在哪里或如何编写async代码,或者如果用户决定注销,我想要做什么实际上可以完成。

这是我当前的代码:

private void DownloadFile(string filePath)
{
    FileInfo myfile = new FileInfo(filePath);

    // Checking if file exists
    if (myfile.Exists)
    {
        // Clear the content of the response
        Response.ClearContent();

        // Add the file name and attachment, which will force the open/cancel/save dialog box to show, to the header
        Response.AddHeader("Content-Disposition", "attachment; filename=" + myfile.Name);

        // Add the file size into the response header
        Response.AddHeader("Content-Length", myfile.Length.ToString());

        // Set the ContentType
        Response.ContentType = "application/octet-stream";

        Response.TransmitFile(filePath);
        Response.Flush();

        try
        {
            myfile.Delete();
        }
        catch { }
    }
}
4

1 回答 1

0

我不知道从 asp.net 应用程序进行异步下载,所以我无法解决这个问题。但是我遇到了足够多的下载问题,总是从同一个地方开始。

首先,从通用句柄 (ASHX) 而不是 Web 表单下载。网络表单希望在请求结束时进行额外处理,这可能会导致问题。您的问题没有说明您使用的是网络表单还是通用处理程序。

其次,始终以 ApplicationInstance.CompleteRequest() 方法调用结束请求。不要使用 Request.Close() 或 Request.End()

这两个更改经常为我清理下载问题。尝试这些更改,看看您是否得到相同的结果。即使您确实得到了相同的结果,这也是一种更好的编码下载方式。

最后,顺便说一句,只在 try-catch 块中捕获适当的异常。

您的代码将是这样的:

public class Handler1 : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        // set from QueryString
        string filePath = "...";

        FileInfo myfile = new FileInfo(filePath);

        // Checking if file exists
        if (myfile.Exists)
        {
            // Clear the content of the response
            context.Response.ClearContent();

            // Add the file name and attachment, which will force the open/cancel/save dialog box to show, to the header
            context.Response.AddHeader("Content-Disposition", "attachment; filename=" + myfile.Name);

            // Add the file size into the response header
            context.Response.AddHeader("Content-Length", myfile.Length.ToString());

            // Set the ContentType
            context.Response.ContentType = "application/octet-stream";

            context.Response.TransmitFile(filePath);
            context.Response.Flush();

            HttpContext.Current.ApplicationInstance.CompleteRequest();

            try
            {
                myfile.Delete();
            }
            catch (IOException)
            { }
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
于 2015-06-11T14:34:36.203 回答