Create public image URL after file upload (Javascript, React)

Viewed 1342

I am using the following code to upload, display, and show the source of an image to a user:

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [file, setFile] = useState(null);

  const handleChange = function loadFile(e) {
    if (e.target.files.length > 0) {
      const file = URL.createObjectURL(e.target.files[0]);
      setFile(file);
    }
  };
  return (
    <div className="App">
      <input type="file" onChange={handleChange} id="upload" accept="image/*" />
      <label htmlFor="upload">
        <div>
          <img alt="uploadImage" src={file} />
        </div>
      </label>
    </div>
  );
}

Working Sandbox here.

Problem

What I would like to do is enable the user to upload their image, and then provide them with a public image URL that would be used as the source of the image being displayed.

With the current code, after upload, the image source is usually something like this: blob:https://fp0tr.csb.app/48a669d9-f9e2-4ea3-811f-c001ac158a1a which I am aware is a result of the URL.createObjectURL() method and only references the local file.

I have tried saving the image source in local storage after upload to maintain its source but this is not a solution since the image will only exist locally. - The requirement is to provide functionality that will let the user reference these images by their source outside of the app.

Is there a method that can be used to create a public image URL that will exist for longer than the life of the page/document it was uploaded in? Is it necessary to use a third-party service for this type of functionality?

EDIT: Another user has provided info about possibly using a web service to achieve this, however, without much context as to what this may look like aside from using the fetch API. - Hoping someone can elaborate.

1 Answers

You aren't uploading the image anywhere.

You are just reading the file, and converting it to a data URL entirely on the client.

To provide a public URL you need to actually upload the file (e.g. using fetch) to a web service which stores the file somewhere that a web server can read it (and the web service can compute the URL that the web server will give it).

There's no need to use a third-party service. You can write your own.

Related