Issues with saving or viewing files being downloaded.

mike55

Contributor
Joined
Mar 26, 2004
Messages
727
Location
Ireland
Hi all

I am using the following code to download a generic file:
Code:
 Private Sub DownloadFile(ByVal filePath As String, ByVal fileName As String)

        Dim liveStream As FileStream = New FileStream(filePath, FileMode.Open, FileAccess.Read)
        Dim buffer(CType(liveStream.Length, Integer)) As Byte

        liveStream.Read(buffer, 0, CType(liveStream.Length, Integer))
        liveStream.Close()
        Response.Clear()
        Response.ContentType = "application/octet-stream"
        Response.AddHeader("Content-Disposition", "attachment; filename=" & fileName)
        Response.BinaryWrite(buffer)
        Response.End()
    End Sub
The file path value is: "c:\test.csv" and the file name value is: "test.csv".

The problems that I am having are:
  1. When I click on the open button, the file gets opened in the web browser in a large number of occasions, on other occasions the file gets opened with excel
  2. When I click the save button, I get the following error message:
    Internet Explorer cannot download UploadItems.aspx?action=csv from x( x= the site location either localhost or a web page). Internet explorer was not able to open this internet site...Please try again later.

I would appreciate it if anyone could help me to solve this problem or point me to a fool proof means of downloading a .csv file while allowing the user to either view or save the file.

Mike55.
 
MIME types

Instead of reading the file data into a buffer and using BinaryWrite, does the following work?

Visual Basic:
Response.Clear()
Response.ContentType = "application/octet-stream"
Response.AddHeader("Content-Disposition", "attachment; filename=" & fileName)
Response.WriteFile(filePath)
Response.End()

I would also suggest trying different MIME types (for ContentType). If you use octet-stream, the web browser tries to infer the MIME type from various properties of the file. If you tell it explicitly what the MIME type is, it may behave more reliably. CSV can be described as:

  1. text/comma-separated-values
  2. text/csv
  3. application/csv
  4. application/excel

Good luck :)
 
Back
Top