应用程序中的WebClient.DownloadFile

时间:2011-12-21 22:11:29

标签: asp.net vb.net

WebClient.DownloadFile有一个问题

在asp.net服务器上,我有以下代码的页面:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
  If Not String.IsNullOrEmpty(Me.Request.QueryString("Tool")) Then
    Dim Subor As String = Server.UrlDecode(Me.Request.QueryString("Tool"))
    Dim SuborCesta As String = Server.MapPath("~/App_Data/Downloads/Images/" & Subor & ".png")
    If IO.File.Exists(SuborCesta) Then
      Response.ClearHeaders()
      Response.ClearContent()
      Response.ContentType = "application/octet-stream"
      Response.AppendHeader("Content-Disposition", "attachment; filename=ToolImage.png")
      Response.WriteFile(SuborCesta)
      Response.End()
    End If
  End If
End Sub

通过这段代码,我下载了桌面程序的图片,我在这里使用:

For i As Integer = 0 To ToolList.Count - 1
  Dim imageAddress As String = String.Empty
  Dim filename As String = String.Empty
  Try
    Dim fileReader As New WebClient()
    imageAddress = ToolList(i).ToolImage
    filename = ToolList(i).ToolFullName & ".png"
    If Not (System.IO.File.Exists(My.Application.Info.DirectoryPath & "\Images\" + filename)) Then
      fileReader.DownloadFile(New Uri(imageAddress), My.Application.Info.DirectoryPath & "\Images\" + filename)
    End If
  Catch ex As Exception
    MessageBox.Show(ex.Message)
  End Try
Next

如果我在浏览器中加载带有查询字符串的页面,则会下载图像。但是如果我在我的程序中使用它,我的磁盘上的图像文件就会被创建,但该文件包含来自我的.aspx页面的html代码。

如何从请求中获取并保存图片?

1 个答案:

答案 0 :(得分:0)

尝试使用适当的MIME类型:

Response.ContentType = "image/png"