Download File Using Javascript/jQuery

前端 未结 28 2935
悲&欢浪女
悲&欢浪女 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:45

    Use an invisible

    To force the browser to download a file it would otherwise be capable of rendering (such as HTML or text files), you need the server to set the file's MIME Type to a nonsensical value, such as application/x-please-download-me or alternatively application/octet-stream, which is used for arbitrary binary data.

    If you only want to open it in a new tab, the only way to do this is for the user to a click on a link with its target attribute set to _blank.

    In jQuery:

    $('a#someID').attr({target: '_blank', 
                        href  : 'http://localhost/directory/file.pdf'});
    

    Whenever that link is clicked, it will download the file in a new tab/window.

提交回复
热议问题