简体   繁体   English

提交下载文件而不是在浏览器中打开

[英]upon submit download file instead of opening in the browser

currently its opening in a same tab, want to download instead of opening.目前它在同一个选项卡中打开,想要下载而不是打开。

<form onsubmit="this.action = document.getElementById('selectedfile').value">
    <select id="selectedfile">
         <option value="/downloads/file1.pdf">File 1</option>
         <option value="/downloads/file2.pdf">File 2</option>
         <option value="/downloads/file3.pdf">File 3</option>
    </select>
    <input type="submit" value="Download" class="grey-btn" class="color:#ffffff, backgroud-color:#ff0000;" />
</form>

I am not sure this can be done with only javascript.我不确定这只能用 javascript 来完成。 You need to serve the file from your server differently.您需要以不同的方式从您的服务器提供文件。

Are you using PHP or something?你使用的是PHP还是什么?

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition

There is a content disposition header you can send to force a download instead of open.您可以发送一个内容处置标头来强制下载而不是打开。

UPDATE:更新:

Okay, so I found a hacky way to do this without messing with the server.好的,所以我找到了一种在不弄乱服务器的情况下执行此操作的hacky方法。 a tags have an optional download attribute you could create and trigger a click on. a标签有一个可选的download属性,您可以创建并触发点击。 Then you can remove the link.然后你可以删除链接。 Here is the sample code:这是示例代码:

        const form = document.getElementById('form');
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            const selectedValue = document.getElementById('selectedfile').value;
            console.log(selectedValue)
            const link = document.createElement('a');
            link.setAttribute('download', selectedValue);
            link.href = selectedValue;
            document.body.appendChild(link);
            link.click();
        });

You would of course remove the onsubmit from the current form you have and add an id (sample is #form).您当然会从您拥有的当前表单中删除 onsubmit 并添加一个 id(示例是 #form)。

I'm fairly sure it's a browser specific setting for only pdf files as modern web browsers have pdf readers built into them.我相当确定它是仅针对 pdf 文件的浏览器特定设置,因为现代网络浏览器内置了 pdf 阅读器。 You can change this for your own browser but not any client who accesses your web page.您可以为自己的浏览器更改此设置,但不能为访问您网页的任何客户端更改。

Here's link for how to do it on:这是有关如何执行此操作的链接:

If your browser isn't here then just search "how to disable built-in PDF viewer for [insert browser here] ".如果您的浏览器不在此处,则只需搜索“如何禁用[在此处插入浏览器] 的内置 PDF 查看”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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