将canvas.toDataURL()作为FormData发送 [英] Sending canvas.toDataURL() as FormData

查看:786
本文介绍了将canvas.toDataURL()作为FormData发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用html2canvas将DOM元素呈现为.png图像,然后我想将其上传到服务器。这是我的代码:

I am trying to use html2canvas to render a DOM element as a .png image, which I then want to upload to the server. Here is my code:

import React, { Component, PropTypes } from 'react';
import html2canvas from 'html2canvas';
import axios from 'axios';


const sendScreenshot = (img) => {
  const config = {
      headers: {
          'content-type': 'multipart/form-data'
      }
  }
  let data = new FormData();
  data.append('screenshot', img);      
  return axios.post('/api/upload', data)
}

export default class Export extends Component {

  printDocument() {
    const input = document.getElementById('divToPrint');
    html2canvas(input).then(canvas => {
      document.body.appendChild(canvas);
      const imgData = canvas.toDataURL('image/png');
      sendScreenshot(imgData)
    });
  }

  ...

我可以看到DOM元素正在被正确转换为图像,因为我可以看到它附加到页面上。

I can see that the DOM element is being converted to an image properly because I can see it appended to the page.

在node.js服务器端,我可以看到表单即将到来,但截图是作为文本字段接收的,而不是作为文件接收。我正在使用multer,我确认我可以正确接收和保存文件上传,至少当我使用Postman时。

On the node.js server end, I can see that the form is coming through, but 'screenshot' is being received as a text field, not as a file. I am using multer and I confirmed that I can properly receive and save file uploads, at least when I use Postman.

所以我想基本的问题是我需要表示我附加到FormData的项目是文件,而不是文本字段。但我无法弄清楚如何做到这一点。我尝试使用附加三个参数,我尝试将imgData转换为如下所示的blob:

So I guess the basic problem is that I need to indicate that the item I am appending to FormData is a file, not a text field. But I can't figure out how to do that. I tried using append with three arguments, and I tried converting the imgData into a blob like so:

const blob = new Blob([img] ,{type:'image / png'});

但结果并没有让我更接近我的想法。

But the results did not put me any closer to what I wanted.

推荐答案

要在POST请求中发送二进制数据,您需要使用 Blob 。 Blob表示原始二进制数据。要获得画布的Blob,您可以使用 toBlob 方法。

To send binary data in a POST request, you want to use a Blob. A Blob represents raw binary data. To get a Blob of a Canvas, you can use the toBlob method.

获得Blob实例后,可以使用 append 方法。 append方法接受Blob实例作为第二个参数。您甚至可以传递一个可选的第三个参数来追加,以指定要与Blob一起发送到服务器的文件名。

Once you have the Blob instance, you can add the Blob to the FormData using the append method. The append method accepts Blob instances as the second argument. You can even pass an optional third argument to append to specify the filename to send with the Blob to the server.

blob将作为文件数据在服务器上接收。

The blob will be received on the server as file data.

这篇关于将canvas.toDataURL()作为FormData发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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