[关闭]
@jeffjade 2017-03-28T13:13:15.000000Z 字数 1767 阅读 1157

JavaScript 实现文件下载

javascript


  1. function downloadFileForIE (contentOrPath, fileName) {
  2. var ifr = document.createElement('iframe')
  3. ifr.style.display = 'none'
  4. ifr.src = contentOrPath
  5. document.body.appendChild(ifr)
  6. ifr.contentWindow.document.execCommand('SaveAs', false, fileName)
  7. document.body.removeChild(ifr)
  8. }

ag-test001
@AgilePoint111

  1. downloadFile (filePath, fileName = true) {
  2. let aLink = document.createElement('a')
  3. aLink.download = fileName
  4. aLink.href = filePath
  5. aLink.click()
  6. }
  1. <a href="path_to_file" download="proposed_file_name">Download</a>

fileUrl = "download/temlate/?key='advice'";

  1. function downloadFile (downloadUrl, key) {
  2. let cForm = document.createElement('form')
  3. cForm.setAttribute('target', '')
  4. cForm.setAttribute('method', 'get')
  5. cForm.setAttribute('style', 'display:none')
  6. cForm.setAttribute('action', downloadUrl)
  7. let cInput = document.createElement('input')
  8. cInput.setAttribute('type', 'hidden')
  9. cInput.setAttribute('name', 'key')
  10. cInput.setAttribute('value', key)
  11. cForm.appendChild(cInput)
  12. document.body.appendChild(cForm)
  13. cForm.submit()
  14. document.body.removeChild(cForm)
  15. }

fileUrl = "download/temlate/?fileName='advice.docx&path=adviceFloder'";

  1. function downloadFile (downloadUrl) {
  2. let cForm = document.createElement('form')
  3. cForm.setAttribute('target', '')
  4. cForm.setAttribute('method', 'post')
  5. cForm.setAttribute('style', 'display:none')
  6. cForm.setAttribute('action', downloadUrl)
  7. document.body.appendChild(cForm)
  8. cForm.submit()
  9. document.body.removeChild(cForm)
  10. }
  1. <form method="get" action="file.doc">
  2. <button type="submit">Download!</button>
  3. </form>
  1. $("#fileRequest").click(function() {
  2. // // hope the server sets Content-Disposition: attachment!
  3. window.location = 'file.doc';
  4. });
  1. <button type="submit" onclick="window.open('file.doc')">Download!</button>

http://stackoverflow.com/questions/11620698/how-to-trigger-a-file-download-when-clicking-an-html-button-or-javascript

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注