简体   繁体   中英

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. You need to serve the file from your server differently.

Are you using PHP or something?

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. a tags have an optional download attribute you could create and trigger a click on. 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).

I'm fairly sure it's a browser specific setting for only pdf files as modern web browsers have pdf readers built into them. 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] ".

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