Kablam
Kablam

Reputation: 2591

Download a file using Javascript

There's this Excel file I want users to be able to download from my server. There must be an easy way to initiate the download of the file after a click on the "Download" button... but I have no clue how to make that happen.

I have this so far: (VBscript and ASP)

<head>
<script type="text/javascript" src="overzicht.js"></script>
</head>

Set fs=Server.CreateObject("Scripting.FileSystemObject")

    if (fs.FileExists("c:\file.xls"))=true then   'fake filename D:
        response.write("<input type='button' value='Download Masterfile' class='button' onclick='exportmasterfile();' /><br />")
    else
        response.write("Masterfile not found. <br />")
    end if

    set fs=nothing

The javascript function is empty.

Upvotes: 10

Views: 70096

Answers (4)

Stephen Quan
Stephen Quan

Reputation: 25936

Here's a VBScript function to download a binary file.

Function SaveUrlToFile(url, path)
  Dim xmlhttp, stream, fso

  ' Request the file from the internet.
  Set xmlhttp = CreateObject("MSXML2.XMLHTTP")
  xmlhttp.open "GET", url, false
  xmlhttp.send
  If xmlhttp.status <> 200 Then
    SaveUrlToFile = false
    Exit Function
  End If

  ' Download the file into memory.
  Set stream = CreateObject("ADODB.Stream")
  stream.Open
  stream.Type = 1 ' adTypeBinary
  stream.Write xmlhttp.responseBody
  stream.Position = 0 ' rewind stream

  ' Save from memory to physical file.
  Set fso = Createobject("Scripting.FileSystemObject")
  If fso.Fileexists(path) Then
    fso.DeleteFile path
  End If
  stream.SaveToFile path

  SaveUrlToFile = true
End Function

Upvotes: 1

Andreas Grech
Andreas Grech

Reputation: 107950

Actually, if you want a 'more-efficient' (and sexier) way, use:

location.href = your_url;

That way, you will save the compiler some time in going up to the location's prototype chain up to the window object.

Upvotes: 21

Nick Retallack
Nick Retallack

Reputation: 19561

If your server is configured to trigger a download for files of that mime type, it's as simple as this:

window.location = your_url

Upvotes: 5

Kablam
Kablam

Reputation: 2591

you're not going to believe this. Found it...

function exportmasterfile()
{   var url='../documenten/Master-File.xls';    
    window.open(url,'Download');  
}

Sorry guys!

Upvotes: 19

Related Questions