Search code examples
ipfs

How to send a file from the browser to a remote IPFS gateway


I have an input field that's calling a _getFile function

<input type="file" class="file" on-change="_getFile"/>

the get file

_getFile(event) {
  this.loading = true;
  const file = event.target.files[0];
  let reader = new window.FileReader()
  reader.onloadend = () => this._saveToIpfs(reader)
  reader.readAsArrayBuffer(file)
 }
}

once we have an array buffer we then call...

_saveToIpfs(data){

}

It is this that I need help with, I want to send the selected file to 'https://ipfs.infura.io:5001/api/v0/add' or 'https://ipfs.io/api/v0/add ' how to do? is it an xhr post? I expect to get an IPFS hash back

The below simple form seems to upload the file and then get disconnected with the error ERR_CONTENT_LENGTH_MISMATCH

<form action="https://ipfs.io/api/v0/add/" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>

I aso tried a classic XHR

_getFile(event) {
const file = event.target.files[0];
var data = new FormData();
data.append('path', event.target.files[0]);
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
    if(request.readyState == 4){
        console.log(request.response)
    }
};
request.open('POST', 'https://ipfs.io/api/v0/add');
request.send(data);
}

with again ERR_CONTENT_LENGTH_MISMATCH


Solution

  • You can use the official js-ipfs-api library. Then you can use the ipfs.files.add function to post your file, since you already have it in an array buffer. If that doesnt work, the js-ipfs-api has a built in Buffer object you can use.