简体   繁体   English

如何强制下载而不是打开文件?

[英]How to force a download instead of opening the file?

So basically, I am using a simple library called HTML2Canvas所以基本上,我使用的是一个名为HTML2Canvas的简单库

This is my current code working great and is being called from an onclick event from a button:这是我当前运行良好的代码,并且正在从按钮的onclick事件中调用:

function saveForm()
{
    html2canvas(document.body, {
            onrendered: function(canvas) {
                document.body.appendChild(canvas);
            }
        });
}

Basically, all it does is take a screen shot and append it to the bottom of the page.基本上,它所做的就是截取屏幕截图并将其附加到页面底部。

There was already a question similar to this, although the answer did not work and the download is always a corrupt jpg file: html2canvas saving as a jpeg without opening in browser已经有一个与此类似的问题,尽管答案不起作用并且下载的始终是损坏的 jpg 文件: html2canvas save as a jpeg without opening in browser

Would there be a way to force a download within this function instead of appending it to the bottom of the page?有没有办法在此功能中强制下载而不是将其附加到页面底部?

  1. Use canvas.toDataURL to get the canvas content as an image src使用canvas.toDataURL获取画布内容作为图像 src
  2. open a window/popup打开一个窗口/弹出窗口
  3. add an <img> to the popup在弹出窗口中添加<img>
  4. assign the image src as src for the image指定图像的src作为src用于图像

function saveForm() {
    html2canvas(document.body, {
        onrendered: function(canvas) {
            var img = canvas.toDataURL("image/png");
            var open = window.open('','','width=500,height=500')
            open.document.write('<img id="img" style="width="400">');
            open.document.getElementById('img').setAttribute('src', img);
        }
    });
}

Tested the code inside onrendered , and it works for sure - but not along with html2canvas.测试了onrendered的代码,它确实有效 - 但不能与 html2canvas 一起使用。

If you right click on the image in the popup -> save image as, the saved image is valid.如果在弹出的图片上右击->图片另存为,保存的图片是有效的。

The reason why I am using setAttribute and not simply src="..." is that if you assign the data src as string the image get corrupted.我使用setAttribute而不是简单的src="..."是,如果您将数据 src 指定为字符串,则图像会损坏。


Edit编辑
I know :( I think you have to set HTTP Headers to force a download, and this can only be done by the server (correct me if I am wrong). I think of a "proxy" on the server like this mockup, download.php :我知道 :( 我认为你必须设置 HTTP Headers 来强制下载,这只能由服务器完成(如果我错了,请纠正我)。我想到了服务器上的“代理”,比如这个模型,下载.php :

<?
$src=$_POST['src'];
header('Content-Type: image/png');
header('Content-Disposition: inline; filename="download.png"');
header('Content-Length: '.count($src));
echo $src;
?>

and call it by并调用它

var img = canvas.toDataURL("image/png");
window.open('download.php?src='+img);

But then you will face a lot of Request-URI Too Large -messages, unless all your canvas-images is in icon-size.但是,除非您的所有画布图像都是图标大小,否则您将面临很多Request-URI Too Large消息。

A second way - and probably the one that would work - would be to save img in a table on the server through ajax, eg calling a script with img src that saves it.第二种方法 - 可能也是可行的方法 - 将通过 ajax 将img保存在服务器上的表中,例如调用带有 img src 的脚本来保存它。 When this call is finished, you could call another server script with the correct headers for image download, including the img src saved just before.完成此调用后,您可以使用正确的图像下载头调用另一个服务器脚本,包括之前保存的 img src。 But this is a more extensive approach you could try yourself..?但这是一种更广泛的方法,您可以自己尝试..?

Here is a solution that builds on the accepted one to enable a download button without server-side code using jQuery.这是一个建立在公认的解决方案之上的解决方案,它可以使用 jQuery 启用下载按钮,而无需使用服务器端代码。

https://codepen.io/nathansouza/pen/OXdJbo https://codepen.io/nathansouza/pen/OXdJbo

function download(url){
  var a = $("<a style='display:none' id='js-downloder'>")
  .attr("href", url)
  .attr("download", "test.png")
  .appendTo("body");

  a[0].click();

  a.remove();
}

function saveCapture(element) {
  html2canvas(element).then(function(canvas) {
    download(canvas.toDataURL("image/png"));
  })
}

$('#btnDownload').click(function(){
  var element = document.querySelector("#capture");
  saveCapture(element)
})

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

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