Base64 image upload - data:image/png


#1

Does anyone has a working sample of a base64 image uploaded via a html form, using adonisjs API?

I’m using a simple html5 feature to capture an image and post it to the server side, using the following steps.

if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
            navigator.mediaDevices.getUserMedia({ video: true }).then(stream => {
                this.video.nativeElement.src = window.URL.createObjectURL(stream);
                this.video.nativeElement.play();
            });
        }
  1. Capturing Image

    var context = this.canvas.nativeElement.getContext(“2d”).drawImage(this.video.nativeElement, 0, 0, 640, 480);
    this.captures.push(this.canvas.nativeElement.toDataURL(“image/png”));

  2. Uploading to the server

     const formData: any = new FormData();
     formData.append("canvas",this.captures[0]);
    
     this.uploadService.upload(formData).subscribe(res => {
         console.log(res);
     });
    
    • Need some help to read the image in the server side and store it in local box. * Tried all the possible ways to read the data using the methods available in the Request API with no luck.

#2

@virk @romain.lanz any thoughts on the above question.?


#3

I’m using Drive from Adonisjs (https://adonisjs.com/docs/4.1/file-system)

const postData = request.post()
const img = Buffer.from(postData.img, 'base64')
await Drive.put(`${path_to_save}')}/${filename_you_want}`, img)

hope its help:grinning:


#4

Thanks @m1ng-s. I had tweak the client side code to submit the encoded image as a form field.


#5

hi.

im trying to do some of the same, but im having some troubles. could you please share your clientside code and controller code?

torgeir


#6

@torgeirbeyer. I’ve added the client side code already above. You have to set the correct content type - application/json to submit it to the server side.