Download File Using Javascript/jQuery

前端 未结 28 2936
悲&欢浪女
悲&欢浪女 2020-11-21 05:11

I have a very similar requirement specified here.

I need to have the user\'s browser start a download manually when $(\'a#someID\').click();

But

28条回答
  •  一整个雨季
    2020-11-21 05:58

    Firefox and Chrome tested:

    var link = document.createElement('a');
    link.download = 'fileName.ext'
    link.href = 'http://down.serv/file.ext';
    
    // Because firefox not executing the .click() well
    // We need to create mouse event initialization.
    var clickEvent = document.createEvent("MouseEvent");
    clickEvent.initEvent("click", true, true);
    
    link.dispatchEvent(clickEvent);
    

    This is actually the "chrome" way solution for firefox (I am not tested it on other browsers, so please leave comments about the compilability)

提交回复
热议问题