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)

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

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 />")
        response.write("Masterfile not found. <br />")
    end if

    set fs=nothing

The javascript function is empty.



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.


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

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

Sorry guys!


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

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") "GET", url, false
  If xmlhttp.status <> 200 Then
    SaveUrlToFile = false
    Exit Function
  End If

  ' Download the file into memory.
  Set stream = CreateObject("ADODB.Stream")
  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

You can download data, but you can't save anything to the local file system with javascript. This is impossible.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.