0

好的,我们有一个 PHP 脚本,它从文件创建下载链接,我们想通过 C# 下载该文件。这适用于进度等,但是当 PHP 页面出现错误时,程序会下载错误页面并将其保存为请求的文件。这是我们在ATM上的代码:

PHP代码:

<?php
$path = 'upload/test.rar';

    if (file_exists($path)) {
        $mm_type="application/octet-stream";
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header("Content-Type: " . $mm_type);
        header("Content-Length: " .(string)(filesize($path)) );
        header('Content-Disposition: attachment; filename="'.basename($path).'"');
        header("Content-Transfer-Encoding: binary\n");
        readfile($path); 
        exit();
    } 
    else {
    print 'Sorry, we could not find requested download file.';
    }
?>

C#代码:

private void btnDownload_Click(object sender, EventArgs e)
    {
        string url = "http://***.com/download.php";
        WebClient client = new WebClient();
        client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
        client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
        client.DownloadFileAsync(new Uri(url), @"c:\temp\test.rar");
    }

    private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        progressBar.Value = e.ProgressPercentage;
    }

    void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
    {
            MessageBox.Show(print);
    }
4

2 回答 2

1

您应该使用此处Header记录的 PHP 函数,而不是打印错误消息。

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404); 

由于您的异步调用的性质,没有WebException抛出。在您的 DownloadFileCompleted 回调中,您可以检查

if(e.Error != null)

您的 e.Error 将包含类似于"The remote server returned an error: (404) Not Found.".

于 2012-11-14T22:57:56.103 回答
1

您需要通过设置标头来通知网络客户端发生了错误,就像您在成功下载时一样。我对PHP不是很熟悉,但是找到了一个401的例子

header('HTTP/1.0 401 Unauthorized', true, 401);

这里

于 2012-11-14T23:01:35.440 回答