You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Plotly默认PNG下载按钮,将图片数据发送至服务器?

重定义Plotly图表默认PNG下载按钮的行为

要替换Plotly图表顶部工具栏里「Download plot as a png」按钮的默认浏览器下载行为,改成通过JavaScript fetch把图片数据发送到服务器,可按以下步骤实现:

核心思路

  1. 等待图表渲染完成后,定位到工具栏中的下载按钮
  2. 拦截默认的点击事件,阻止浏览器下载操作
  3. 调用Plotly.toImage生成图片数据,再通过fetch发送到服务器

完整代码示例

HTML代码

<script src="https://cdn.plot.ly/plotly-2.16.2.min.js"></script>
<div id="myDiv"></div>

JavaScript代码

// 初始化Plotly图表
Plotly.newPlot('myDiv', [{x: [1, 2, 3, 4], y: [10, 15, 13, 17], mode: 'markers'}])
  .then(() => {
    // 定位工具栏中的PNG下载按钮
    const downloadBtn = document.querySelector('#myDiv .modebar-btn[data-title="Download plot as a png"]');
    if (downloadBtn) {
      // 替换默认点击行为
      downloadBtn.onclick = (e) => {
        // 阻止默认下载动作
        e.preventDefault();
        e.stopPropagation();
        
        // 生成PNG格式的图片数据(可调整width/height参数)
        Plotly.toImage('myDiv', {format: 'png', width: 800, height: 600})
          .then((imgData) => {
            // 将base64格式的图片转为Blob(方便服务器处理)
            const blob = dataURItoBlob(imgData);
            // 构建FormData对象
            const formData = new FormData();
            formData.append('plotImage', blob, 'plot.png');
            
            // 发送到服务器接口,替换为你的实际地址
            fetch('/upload-plot', {
              method: 'POST',
              body: formData
            })
            .then(res => res.json())
            .then(result => {
              console.log('图片上传成功:', result);
              // 可添加成功提示逻辑,比如弹出通知
            })
            .catch(err => {
              console.error('图片上传失败:', err);
            });
          });
      };
    }
  });

// 辅助函数:把base64数据转为Blob格式
function dataURItoBlob(dataURI) {
  const byteString = atob(dataURI.split(',')[1]);
  const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
  const ab = new ArrayBuffer(byteString.length);
  const ia = new Uint8Array(ab);
  for (let i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }
  return new Blob([ab], {type: mimeString});
}

关键细节说明

  • 必须在Plotly.newPlot的then回调里操作按钮,确保图表完全渲染,避免找不到DOM元素
  • 按钮选择器.modebar-btn[data-title="Download plot as a png"]适配Plotly 2.16.2版本,若使用其他版本,可通过浏览器开发者工具查看按钮的实际类名和属性调整
  • 如果服务器支持直接接收base64字符串,可跳过Blob转换步骤,直接把imgData作为请求体发送
  • 替换/upload-plot为你的实际服务器接口地址,确保后端能正确处理文件上传请求

内容的提问来源于stack exchange,提问作者Basj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 01:05:27