仅使用Javascript(无服务器端)将textarea内容下载为文件 [英] Download textarea contents as a file using only Javascript (no server-side)

查看:169
本文介绍了仅使用Javascript(无服务器端)将textarea内容下载为文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被要求制作一个下载按钮,将文本的内容下载到与文件相同的页面上,浏览器的另存为...对话框显示。复制/粘贴会做的很好,但这是一个要求。

I am being asked to make a "download" button that downloads the contents of a textarea on the same page as a file, with the browser's "Save As..." dialog showing up. Copy/paste would do the job just fine, but it is a "requirement".

现在,我只是把文本的内容发布到服务器,回到内容处置:附件。有没有办法只用客户端Javascript呢?

Right now, I am just posting the contents of the textarea to the server, which echos them back with Content-disposition: attachment slapped on. Is there a way to do this with just client-side Javascript?

推荐答案

这可能是您正在寻找的:
http://thiscouldbebetter.wordpress.com/2012/12/18/loading -editing-and-saving-a-text-file-in-html5-using-javascrip /

This may be what you are looking for: http://thiscouldbebetter.wordpress.com/2012/12/18/loading-editing-and-saving-a-text-file-in-html5-using-javascrip/

它使用浏览器的下载对话框,但仅支持FF和Chrome,现在可能还有更多的浏览器?

It uses the browser's download dialogue, but supports only FF and Chrome, and maybe more browsers now?

编辑:

评论时,我将嵌入文章中的代码:

As commented I will embed the code from the article:

function saveTextAsFile()
{
    var textToWrite = //Your text input;
    var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
    var fileNameToSaveAs = //Your filename;

    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    if (window.webkitURL != null)
    {
        // Chrome allows the link to be clicked
        // without actually adding it to the DOM.
        downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
    }
    else
    {
        // Firefox requires the link to be added to the DOM
        // before it can be clicked.
        downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
        downloadLink.onclick = destroyClickedElement;
        downloadLink.style.display = "none";
        document.body.appendChild(downloadLink);
    }

    downloadLink.click();
}

这篇关于仅使用Javascript(无服务器端)将textarea内容下载为文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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