Download a picture from a website link and transfer it to the IPFS network

Currently, I am facing an issue while attempting to fetch an image from a different website and then uploading it to IPFS using Next.js. Despite configuring CORS in next.config.js to enable the application to retrieve the image, everything seems to be functioning correctly. I am utilizing Axios to save the retrieved file in a File object; however, my IPFS upload is failing.

/* pages/test.js */
import Axios from 'axios';
import { create } from 'ipfs-http-client';

const client = create('https://ipfs.infura.io:5001/api/v0');

export default function Test () {

  async function uploadImageToIPFS (url) {
    const file = await Axios
      .get(url, { responseType: 'blob' })
      .then(response => {
        console.log(response.data);
        new File([response.data], "dummy");
      })
      .catch(ex => {
        console.error(ex);
    });
    try {
      const added = await client.add(
        file,
        {
          progress: (prog) => console.log(`received: ${prog}`)
        }
      )
      const url = `https://ipfs.infura.io/ipfs/${added.path}`;
      console.log(url);
      } catch (error) {
        console.log('Error uploading file: ', error);
      }
  }

  return (
    <div onClick={() => uploadImageToIPFS('https://media-exp1.licdn.com/dms/image/C4E03AQFDEyGQpYnEwA/profile-displayphoto-shrink_100_100/0/1572360635415?e=1635379200&v=beta&t=W3cLmvalBVyArWAwTnbyeEWrJNbc9eKT7IJgoPhO22w')}>
      Click to upload
    </div>
  );
}

The current error message being displayed is:

test.js?142b:31 Error uploading file:  Error: Unexpected input: undefined
    at normaliseInput (normalise-input.js?ce8a:31)
    at normaliseInput.next (<anonymous>)
    at multipartRequest (multipart-request.browser.js?542b:25)
    at addAll (add-all.js?74f2:28)
    at addAll.next (<anonymous>)
    at last (index.js?9975:13)
    at Object.add (add.js?59bb:23)
    at _callee$ (test.js?142b:22)
    at tryCatch (runtime.js?96cf:63)
    at Generator.invoke [as _invoke] (runtime.js?96cf:294)
    at Generator.eval [as next] (runtime.js?96cf:119)
    at asyncGeneratorStep (asyncToGenerator.js?2297:3)
    at _next (asyncToGenerator.js?2297:25)

I'm unsure what mistake I might have made. Any guidance would be appreciated.

Answer №1

When working with files, it is important to understand that they are essentially buffers containing binary data. To achieve the desired functionality, the following code snippet can be used:

const file = await Axios
      .get(tmpNFT.image, { responseType: 'blob' })
      .then(response => {
        return response.data;
      })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

remove MongoDB entry using unique identifier

I am currently working on a blog project using nodejs, express, and mongodb. My goal is to delete a specific document by its ID. For instance, if I want to remove a blog post with the ID 52976b1b0855c7e81a6192e9, I would make a request to localhost:3000/bl ...

Warning: React detects a missing dependency within an interval in the effect

A webpage I developed using React and Next.js has the following structure. import Head from 'next/head'; import { useEffect, useState } from 'react'; import Header from '../components/Header'; export default function Home() { ...

FilterTextBoxExtender in AJAX enables the input of carriage returns

I need assistance with a multi-line text box that I'm using an AJAX FilteredTextBoxExtender on to restrict user input to just numbers. However, I also want users to be able to add a new line by pressing the enter key. I've looked around for a sol ...

What is the best way to insert a Button within a Tab while ensuring that the indicator remains in the appropriate tab?

Is it possible to include a button inside a Tab? When I click on "Homepage", the tab switches correctly with the indicator showing on the right tab. However, when I click on "Profile", the indicator moves to the logout button instead. How can I fix this ...

Finding all items in an array in Cypress and validating them using JavaScript assertions

After making an API call, I have received an array response that includes the following information: [ { "IsDatalakeEnabled": true, "RecoveryHr": { "IsRecoveryHREnabled": false, &quo ...

What is the best way to give a fixed height to Card content in Material UI? Is CSS the way to go?

I've been struggling with a design issue involving Material-UI cards used to display News. The problem arises when the paragraph section of the card occupies multiple lines of text. When it spans two lines, there is a 10px spacing between the paragrap ...

Utilizing TIMING=1 with eslint to evaluate rule efficiency on Windows operating system

On the official ESLint website, there is a section titled Per-rule Performance. It explains that "setting the TIMING environment variable will prompt the display of the ten longest-running rules upon linting completion, showing their individual runn ...

Only a fragment of the .attr() method

I am trying to work with an image HTML block <img src="folder1/folder2/folder3/logo1.png"> situated inside a large div similar to this structure <div id="editorial"> <div id="img_editorial"><img src="folder1/folder2/folder3/logo1. ...

Having some trouble in the production process, would greatly appreciate any suggestions or clues

While deploying my ecommerce app on Vercel, I encountered an error related to authentication using Next-auth. The specific error message is: TypeError: Cannot read properties of null (reading 'id') at a (/vercel/path0/.next/server/app/dashboa ...

Creating a CSS animation to repeat at regular intervals of time

Currently, I am animating an SVG element like this: .r1 { transform-box: fill-box; transform-origin: 50% 50%; animation-name: simpleRotation,xRotation; animation-delay: 0s, 2s; animation-duration: 2s; animation-iterat ...

Trigger an event upon completion of a write operation in AngularJS

I want to trigger a search after my user finishes typing (without hitting enter) in AngularJS. Here is a simplified version of my HTML: <div ng-class="input-append" ng-controller="searchControl"> <input type="text" ng-model="ajaxSearch" ng-cha ...

What is the best way to adjust the size of an image as I navigate down a webpage?

I've been working on designing a navigation bar for a website, but I'm running into some issues. My goal is to have the logo shrink as the user scrolls down the site. I've experimented with webkit animations and various javascript/jQuery fun ...

Is it possible to programmatically open the Firefox browser console using JavaScript within an extension?

I attempted to link toJavaScriptConsole() with a button, however it is not functioning (undefined reference error) Is there a way to code an XUL button that will launch the firefox browser console, allowing us to view logs from the extension? ...

The Slice method is malfunctioning after the array has been filtered

I am currently working on creating a news portal app using Next JS, Redux, mongoose, and Express. My Issue is: While I am able to filter specific items from an array successfully, I encounter problems when attempting to display a specific number of items, ...

What is causing my button to act in this way?

Initially, the website redirects to an undefined URL and then to test.com. I am looking for a way to implement a redirection sequence from to and finally to <head> <script type="text/javascript"> <!-- function popup(url ...

What occurs when Render() is called during animation in React?

Curious about how React handles rendering during a component's animation? Let's explore an example where a component is re-rendered due to a state change triggered during its animation. Imagine a scenario where a component's animation lasts ...

What is the best way to create a JavaScript animation for altering the width of a div element?

Need help with creating a dynamic poll chart based on YES and NO votes? Check out this project where you can visually see the results by clicking HERE. Looking to add some animation effects to your poll? You can achieve a smooth transition using CSS with ...

User events in the fullCalendar

I'm feeling stuck. I currently have a basic fullCalendar setup for the User model in Rails. I want to add 2 buttons, allowing the User to separate the calendar into two views. One view would display only their own events, while the other would show al ...

Update the PHP webpage dynamically by utilizing AJAX and displaying the PHP variable

I am working on a PHP page that includes multiple queries, and I would like to be able to include this page in my index.php file and display the results with an automatic refresh similar to the Stack Overflow inbox feature. Is there a way to achieve this ...

Interactive Thumbnail Previews

There seems to be an issue with the thumbnail links on my page. The leftmost and rightmost links work fine, but the middle ones are not functioning properly when clicked. The PHP code used to generate these links is the same for all of them, so it's p ...