完整的下载文件

Protected Sub downloadbyID(ByVal ID As Integer)
        Dim prepareSql As String = "select * from mfg_rfqdoc where id=" + ID.ToString

        Dim ds As DataSet = binddata(prepareSql)
        Dim file() As Byte = ds.Tables(0).Rows(0).Item("binfile")
        Dim name As String = ds.Tables(0).Rows(0).Item("attachname")
        Try
'这里的地址很烦,注意烦人的格式
            Dim stream As Stream = New FileStream("MFGQuotation/" + name, FileMode.CreateNew)
            stream.Write(file, 0, file.Length)
'写完文件,记住关闭流,否则下载时会提示文件正在被使用
            stream.Close()

        Catch ex As Exception

        End Try

        Dim fullfilename = Server.MapPath("~\\MFGQuotation\\" + name)
        Dim downloadfile As FileInfo = New FileInfo(fullfilename)
        Response.Clear()
        Response.ClearHeaders()
        Response.Buffer = False
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(downloadfile.FullName, System.Text.Encoding.UTF8))
'这里注意一下,downloadfile.fullname可改为你想保存的文件名,即客户端保存时的名称
        Response.AppendHeader("Content-Length", downloadfile.Length.ToString())
        Response.ContentType = "application/octet-stream "
        Response.WriteFile(downloadfile.FullName)
        Response.Flush()
'文件下载完记得删掉,因为本来就系临时文件,不删掉的话,下次新建文件时可能抛出文件已存在的错
        System.IO.File.Delete("MFGQuotation/" + name)
'这个end很神奇,end之后的任何代码都不会运行,就像一个return,所以上面那句不能写在end之后
        Response.End()



    End Sub
End Class


只要把mappath替换就ok,如果要从数据库取文件,那么要先把文件保存在数据库

你可能感兴趣的:(下载文件)