0

So I created an image using canvas. And I want to pass the image using ajax. I know how to do it using form but this time I'm not using one. This is my code for creating image.

      var video = document.querySelector('video')
      , canvas;

      var img = document.querySelector('img') || document.createElement('img');
      var context;
      var width = video.offsetWidth
        , height = video.offsetHeight;

      canvas = canvas || document.createElement('canvas');
      canvas.width = width;
      canvas.height = height;

      context = canvas.getContext('2d');
      context.drawImage(video, 0, 0, width, height);

      img.src = canvas.toDataURL('image/png');
      document.body.appendChild(img);

the "img" variable is my created image. This is my code of passing image using ajax

var form = $('#fileUploadForm')[0];
      var data = new FormData(form);

      $.ajax({
          type: "POST",
          enctype: 'multipart/form-data',
          url: "/api/file/upload",
          data: data,
          processData: false, //prevent jQuery from automatically transforming the data into a query string
          contentType: false,
          cache: false,
          success: (data) => {
              $("#listFiles").text(data);
          },
          error: (e) => {
              $("#listFiles").text(e.responseText);
          }
      });

I tried other tutorials by creating a new FormData but it doesn't seem to work. I also tried assigning value to input file type.But it doesn't work and others doesn't recommend it due to future security problems. Hoping you could help me.

CaptainHarry
  • 193
  • 1
  • 2
  • 8
  • How about posting the data URL directly then convert it to file on the server side? – Ricky Mo Oct 11 '18 at 03:28
  • what is the data URL? – CaptainHarry Oct 11 '18 at 03:29
  • It means `canvas.toDataURL('image/png')`, which is a string in plain text that represent the image data. If you have control on the server side, you can send it to the server via AJAX and convert it to file. – Ricky Mo Oct 11 '18 at 03:30
  • [this post](https://stackoverflow.com/questions/4998908/convert-data-uri-to-file-then-append-to-formdata) might help you – Ricky Mo Oct 11 '18 at 03:35
  • I tried to do it and did some modifications. But it still doesn't work. I posted [another question](https://stackoverflow.com/questions/52753028/ajax-send-canvas-image-to-controller) hope you could help me. Thank you! – CaptainHarry Oct 11 '18 at 06:02

0 Answers0