Force Download fails when I select "Open" but works fine when I select "Save"

M

Michael

I have a problem forcing files to download. If I select Save the document is
saved with no problems. If I select "Open" the document is empty or I get a
"File not found" error from the application opening the file...

Code:

function UTIL_ForceDownloadFile(strFileName, strFileSaveName)
Response.Buffer = True
Dim strFileSize
Const adTypeBinary = 1
Response.Clear

'#Code Find File Size
dim fso, fileObject
Set fso = Server.CreateObject("Scripting.FileSystemObject")
Set fileObject = fso.GetFile(Server.MapPath(strFileName))
strFileSize = fileObject.Size
Set fileObject = Nothing
Set fso = Nothing

dim objStream, strFileType, ContentType
Set objStream = Server.CreateObject("ADODB.Stream")
objStream.Open
objStream.Type = adTypeBinary
objStream.LoadFromFile Server.MapPath(strFileName)

strFileType = lcase(Right(strFileName, 4))

Select Case strFileType
Case ".asf"
ContentType = "video/x-ms-asf"
Case ".avi"
ContentType = "video/avi"
Case ".doc"
ContentType = "application/msword"
Case ".zip"
ContentType = "application/zip"
Case ".xls"
ContentType = "application/vnd.ms-excel"
Case ".gif"
ContentType = "image/gif"
Case ".jpg", "jpeg"
ContentType = "image/jpeg"
Case ".wav"
ContentType = "audio/wav"
Case ".mp3"
ContentType = "audio/mpeg3"
Case ".mpg", "mpeg"
ContentType = "video/mpeg"
Case ".rtf"
ContentType = "application/rtf"
Case ".pdf"
ContentType = "application/pdf"
Case ".htm", "html"
ContentType = "text/html"
Case ".asp"
ContentType = "text/asp"
Case ".txt"
ContentType = "text/plain"
Case Else
ContentType = "application/octet-stream"
End Select

Response.AddHeader "Content-Disposition", "attachment; filename=" &
strFileSaveName
Response.AddHeader "Content-Length", strFileSize

Response.ContentType = ContentType
Response.Charset = "UTF-8"
Response.BinaryWrite objStream.Read
Response.Flush
objStream.Close
Set objStream = Nothing
response.end
end function
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top