Search code examples
javascriptjquerynode.jsangularipfs

Sending image Buffer through API to add to IPFS


I am trying to upload an image to IPFS. and i am doing like this :

I upload the image from my web UI, convert it to buffer in my angular component, send it through a put/post request ( with httpclient ) to my nodeJS Express server, my server connects to the IPFS network and saves the image.

The problem i get is that i can't upload the image to IPFS and i keep getting this error :

Content submission error: Error: Invalid arguments, data must be an object, Buffer or readable stream 

This is how i am getting the buffer made before sending :

const that = this;
      that.ConfirmButtonDisabled=true;
        let NativeInput = jQuery(this.ImageInput.nativeElement);
        NativeInput.trigger('click');
        NativeInput.change('file-select',function (file) {
            const reader = new FileReader();
            reader.onload = (e) => {
                let file=reader.result
                let buffer = new Buffer(file);
                const buff: ArrayBuffer = buffer.buffer;
                that.CustomerInfo["KImage"] = buff;
                console.log("read the file into buffer", that.CustomerInfo)
                that.ConfirmButtonDisabled=false;
            }
            reader.readAsArrayBuffer(NativeInput.prop('files')[0]);
            console.log(NativeInput.prop('files')[0])
            that.SelectedImage = NativeInput.prop('files')[0].name;
        })

This way when logging in the browser i get something like this : image:ArrayBuffer(6924) {}

If i don't use the buffer.buffer i get a uint8array logged like this : image:Uint8Array(6924) [255, 216, 255, 224, 0, 16, 74, 70, 73, 70, ... ]

this last version doesn't show up the same way if i log it on the server side, every element of the array changes to something like \u0000 as if they were ascii or utf8 characters ( this might be the work of the console.log() function but i am not sure ) ex : ����\u0000\u0010JFIF\u0000\u0001\u0001\u0000\u0000\u0001\u0000\u0001\u0000\u0000��\u0000�\u0000\t\u0006\u0007\r\r\r\u0010\r\r\u0010\u000f\r\r\r\u000e\r\r\r\r

In both these cases IPFS outputs the same error.

NOTE : I did work with IPFS directly ( no nodeJS server ) with a web client, and it worked. So i presumed the same code would work since it is all javascript.

How do i do it ? how do i correctly send the buffer ( or image ) from my angular 5 client to IPFS through nodeJS ;


Solution

  • I fixed this by sending uint8array via HTTP and creating a buffer with buffer.from inside my nodeJs code. a rather easy fix.