简体   繁体   中英

How can I send a copy of a user generated png to my backend?

I am building a site that allows users to create customized graphics and then download them directly from the page.

I am doing this via the user customizing an svg via a javascript powered form which is then made into a PNG before downloading.

However, now I want to store a copy of the png that the user created so that I can display it on the site's home page. What is the best way to store a copy of the dynamically created graphic? AJAX? HTTP Request? Both are very foreign topics to me so I am unsure how to go about it from here.

For reference here is the code that builds the PNG from the svg and then triggers the download for the user.

var svg = document.getElementById("bg2");
var canvas = document.querySelector("canvas");

function triggerDownload (imgURI) {
  var evt = new MouseEvent('click', {
    view: window,
    bubbles: false,
    cancelable: true
  });
    if(document.getElementById("name").value=="null" || document.getElementById("name").value=="") {
    var un = "MakeAGraphic";
  } else {
    var enteredName = document.getElementById("name").value.replace(/[^a-zA-Z ]/g, "");
    var un = `${enteredName}_MakeAGraphic`
  }
  var a = document.createElement('a');
  a.setAttribute('download', `${un}.png`);
  a.setAttribute('href', imgURI);
  a.setAttribute('target', '_blank');

  a.dispatchEvent(evt);
}

btn.addEventListener('click', function () {
  var canvas = document.getElementById('canvas');
  var ctx = canvas.getContext('2d');
  var data = (new XMLSerializer()).serializeToString(svg);
  var DOMURL = window.URL || window.webkitURL || window;

  var img = new Image();
  var svgBlob = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
  var url = DOMURL.createObjectURL(svgBlob);

  img.onload = function () {
    ctx.drawImage(img, 0, 0);
    DOMURL.revokeObjectURL(url);

    var imgURI = canvas
        .toDataURL('image/png')
        .replace('image/png', 'image/octet-stream');

    triggerDownload(imgURI);
  };

  img.src = url;
});

agree to that answer mentioned by @showdev.

Call canvas.toBlob(callback, mimeType, qualityArgument);

then call formData.append("an-image", blob);

then upload formData using the AJAX or fetch API.

see the documents at

https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob

https://developer.mozilla.org/en-US/docs/Web/API/FormData/append

https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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