How to upload a screenshot using html2canvas?

后端 未结 3 1093
遇见更好的自我
遇见更好的自我 2020-12-01 08:29

Using html2canvas how can I save a screen shot to an object? I\'ve been exploring the demos, and see that the function to generate the screenshot is generated as follows:

3条回答
  •  庸人自扰
    2020-12-01 09:21

    I have modified and annotated the method from this answer. It sends only one file, with a given name, composed from a element.

    if (!('sendAsBinary' in XMLHttpRequest.prototype)) {
      XMLHttpRequest.prototype.sendAsBinary = function(string) {
        var bytes = Array.prototype.map.call(string, function(c) {
          return c.charCodeAt(0) & 0xff;
        });
        this.send(new Uint8Array(bytes).buffer);
      };
    }
    
    /*
     * @description        Uploads a file via multipart/form-data, via a Canvas elt
     * @param url  String: Url to post the data
     * @param name String: name of form element
     * @param fn   String: Name of file
     * @param canvas HTMLCanvasElement: The canvas element.
     * @param type String: Content-Type, eg image/png
     ***/
    function postCanvasToURL(url, name, fn, canvas, type) {
      var data = canvas.toDataURL(type);
      data = data.replace('data:' + type + ';base64,', '');
    
      var xhr = new XMLHttpRequest();
      xhr.open('POST', url, true);
      var boundary = 'ohaiimaboundary';
      xhr.setRequestHeader(
        'Content-Type', 'multipart/form-data; boundary=' + boundary);
      xhr.sendAsBinary([
        '--' + boundary,
        'Content-Disposition: form-data; name="' + name + '"; filename="' + fn + '"',
        'Content-Type: ' + type,
        '',
        atob(data),
        '--' + boundary + '--'
      ].join('\r\n'));
    }
    

提交回复
热议问题