HTML附加/替换下载文件的内容

时间:2013-07-17 17:45:48

标签: vb.net iis-7 download mime

这让我非常困惑,因为代码在开发环境中工作并在本地部署到IIS。但是,当部署到我们的测试服务器上时,纯文本下载的内容将替换为页面回发。要生成的代码;

Protected Sub _uiDownloadLBtn_Click(ByVal sender As Object, ByVal e As EventArgs) Handles _uiDownloadLBtn.Click
    Try
        'respond with the export details
        RespondWithFile(ExportFilePath)

    Catch ex As Exception
        'log the exception
        _logger.ErrorException("There was a problem trying to download the export file", ex)
        lblMessage.Text = "There was a problem trying to download the file"
    End Try
End Sub

Public Sub RespondWithFile(ByVal fileName As String)
    RespondWithFile(fileName, fileName)
End Sub

Public Sub RespondWithFile(ByVal fileName As String, ByVal downloadFileName As String)
    Try
        ' don't do anything if we have nothing to work with
        If String.IsNullOrEmpty(fileName) OrElse Not File.Exists(fileName) Then
            Return
        End If

        Dim fileDetails As New FileInfo(fileName)
        Dim response As HttpResponse = HttpContext.Current.Response
        response.Clear()
        response.AddHeader("Content-Disposition", "attachment; filename=" & Path.GetFileName(downloadFileName))
        ' strip out the path
        response.AddHeader("Content-Length", fileDetails.Length.ToString())
        response.ContentType = "text/plain"
        response.WriteFile(fileName)
        'response.End()
        HttpContext.Current.ApplicationInstance.CompleteRequest()

    Catch tex As ThreadAbortException
        ' log as warning and stop it from bubbling back up the call stack
        _logger.WarnException("ThreadAbortException thrown", tex)
        Thread.ResetAbort()
    End Try
End Sub

正如您所看到的,我明确指定了text/plain的MIME类型,并尝试同时调用response.End()HttpContext.Current.ApplicationInstance.CompleteRequest()

原来的行为是传输文件的内容后跟一个空行然后回发。在完全擦除已部署的内容并将更新的代码复制到IIS服务器之后,回发内容随后替换了下载内容。

逻辑上,要查看的位置是IIS实例,但应用程序仅使用最基本的设置。 IIS版本为7,.NET框架为2.0。没有设置其他IIS配置。

想法?

1 个答案:

答案 0 :(得分:0)

我找到了“一个”解决方案。通过将内容类型转换为"application/pdf"并将文件扩展名转换为".csv",我可以强制将文件的内容传送与回发内容分开。这适用于浏览器虽然在FireFox中有一个不幸的效果,它要求用户使用Adobe Reader(“application / pdf”内容的注册应用程序)打开文本文件。这对我们的客户无关紧要,但可能不适合其他客户。

这确实在IIS中的MIME配置中确定了原因,尽管我仍然对导致它的确切设置感到困惑。我曾尝试将".txt"明确设置为text/plain而将".csv"设置为text/csv(有效但通常未注册的MIME类型)并且都不起作用。我想知道在这里是否有某种MIME类型的层次/偏好。

不过,至少还有一个可行的解决方案。我希望这有助于其他人。