简体   繁体   中英

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.

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';    
    window.open(url,'Download');  
}

Sorry guys!

如果您的服务器配置为触发下载该mime类型的文件,那么就像这样简单:

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")
  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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM