使用Javascript或JQuery的自定义下载名称 [英] Custom download name with Javascript or JQuery

查看:59
本文介绍了使用Javascript或JQuery的自定义下载名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何在HTML中使用< a href ="file.jpg" download ="name"> 块,但是恐怕这不适用于该项目.

I know how to use the <a href="file.jpg" download="name"> block in HTML, but I'm afraid that will not work for this project.

我想有一个下载链接,该链接(毫无疑问)将下载文件.我还要在屏幕上显示一个文本框,允许用户命名要下载的文件.

I would like to have a download link which will (unsurprisingly) download a file. I would also like a text box on the screen that will allow the user to name the file that thay download.

该网站看起来像这样:

Name:<input type="text" name="Name" value="Custon Name">
<br>
<button type="button">Download</button>

我希望< button> 块使用 onclick"function()" 来下载文件.该功能将从文本框中获取文本,并在下载文件时使用它来命名文件.我需要帮助的事情是找到一种使用Javascript或JQuery命名文件的方法,就像 download ="name" 一样.

I want the <button> block to use onclick"function()" in order to download the file. The function will get the text from the text box and use it to name the file when downloading it. The thing I need help with is finding a way to name the file using Javascript or JQuery in the same way that download="name" would.

我已经寻找了一段时间,但没有运气.这个项目可能吗?如果是这样,怎么做?

I've looked for a while for a way to do this, but no luck. Is this project possible? If so, how is it done?

推荐答案

您可以通过动态创建 a 元素并将输入的名称设置为其 download 来做到这一点属性:

Well you can do it by creating the a element dynamically and setting the inputted name as its download attribute:

function downloadIt() {
  var name = document.getElementsByName("Name")[0].value;
  if (name && name !=='') {
    var link = document.createElement('a');
    link.download = name;
    link.href ="file.png";  
    link.click();
  }
}

这是正在运行 Demo ,您可以选中我的答案也可以使用JavaScript下载文件.

This is a working Demo and you can check my answer for file download with JavaScript too.

这篇关于使用Javascript或JQuery的自定义下载名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆