How to access the Infura IPFS api in angular

60 Views Asked by At

I want to send a file to Infura's IPFS API in an angular application. I understand ipfs-http-client is deprecated so I'm trying to make a call to the API using POST.

App component:

  onFileSelected(event: Event){
    var inputElement = event.target as HTMLInputElement;
    if (inputElement?.files && inputElement.files.length > 0) {

      this.fcUploadFile = inputElement.files[0];

      var reader = new FileReader();

      reader.onload = (e) => {
        var fileContent = e.target?.result;

        this.IpfsService.uploadToIpfs(fileContent);
        console.log("File content: ", fileContent);
      };

      reader.readAsArrayBuffer(this.fcUploadFile);

      console.log('File selected:', this.fcUploadFile);
    } else {
      console.error('No file selected.');
    }
  }

(The output from my console is empty)

IPFS service:

export class IpfsService {

  private readonly apiUrl: 'https://ipfs.infura.io:5001/api/v0/add?pin=true';

  constructor(private http: HttpClient){}

  uploadToIpfs(file: any){
    const formData = new FormData();
    formData.append('file', file); //formData

    const headers = new HttpHeaders({
      Authorization: 'Basic '+ btoa('API KEY:API SECRET')
    });

    var res = this.http.post(this.apiUrl, formData, { headers });
    console.log(res); //=> Empty observable displayed
    return res;
  }
}

I tried to make a post request without using 'ipfs-http-client'. I was expecting to receive the cid for the uploaded file, but the result is empty

1

There are 1 best solutions below

0
COM On

ipfs-http-client still works:

const projectId = 'ID';
    const projectSecret = 'SECRET';
    const auth = 'Basic ' + btoa(projectId + ':' + projectSecret);

    const cl = create({
      host: 'ipfs.infura.io',
      port: 5001,
      protocol: 'https',
      headers: {
        authorization: auth,
      },
    });

    cl.add(f).then((res: any) => {
      console.log("IPFS Response: " , res.path);
      return res.path;
    });