资源解释为Document但使用MIME类型image / octet-stream传输

时间:2016-08-24 14:11:17

标签: google-visualization

使用以下代码保存Google图表。但是它被下载为文件而不是图像,它正在抛出

"Resource interpreted as Document but transferred with MIME type image/octet-stream: "data:image/octet-stream;base64,..."

代码:

function getImgData(chartContainer) {
    var chartArea = chartContainer.getElementsByTagName('div')[1];
    var svg = chartArea.innerHTML;
    var doc = chartContainer.ownerDocument;
    var canvas = doc.createElement('canvas');
    canvas.setAttribute('width', chartArea.offsetWidth);
    canvas.setAttribute('height', chartArea.offsetHeight);


    canvas.setAttribute(
        'style',
        'position: absolute; ' +
        'top: ' + (-chartArea.offsetHeight * 2) + 'px;' +
        'left: ' + (-chartArea.offsetWidth * 2) + 'px;');
    doc.body.appendChild(canvas);
    canvg(canvas, svg);
    var imgData = canvas.toDataURL("image/png");
    canvas.parentNode.removeChild(canvas);
    return imgData;
  }

  function saveAsImg(chartContainer) {
    var imgData = getImgData(chartContainer);
    window.location = imgData.replace("image/png", "image/octet-stream");
  }

1 个答案:

答案 0 :(得分:1)

您可以使用带有download属性的锚标记来指定文件名

并且大多数图表都有getImageURI方法

另外,不要认为需要replace("image/png", "image/octet-stream")

请参阅以下工作代码段...

google.charts.load('current', {
  callback: function () {
    var chart = new google.visualization.PieChart(document.getElementById('chart_div'));

    google.visualization.events.addListener(chart, 'ready', function () {
      // set anchor tag
      var saveLink = document.getElementById('saveLink');
      saveLink.href = chart.getImageURI();

      // cause download to occur
      saveLink.click();
    });

    chart.draw(google.visualization.arrayToDataTable([
      ['Task', 'Hours'],
      ['A', 19.2],
      ['B', 30.8],
      ['C', 50.0]
    ]), {
      height: 200,
      chartArea: {
        top: 24
      },
      legend: 'none',
      pieHole: 0.4,
      theme: 'maximized',
      width: 200
    });
  },
  packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
<a id="saveLink" download="chart.png">Save Chart</a>