📜  react-file-base64 - Javascript (1)

📅  最后修改于: 2023-12-03 15:19:45.205000             🧑  作者: Mango

react-file-base64

react-file-base64 is a simple utility that converts files to base64 strings in your React application. It simplifies handling file uploads and allows you to easily send them to an API or store them in a database.

Installation

You can install react-file-base64 using npm:

npm install react-file-base64
Usage

Using react-file-base64 is very simple. First, import the utility:

import FileBase64 from 'react-file-base64';

Then, use it in your component by passing a setter function to the onDone prop to receive the file as a base64 string:

<FileBase64
  multiple={ false }
  onDone={ (files) => console.log(files.base64) }
/>

You can set the multiple prop to true if you want to allow users to upload multiple files at once.

Example

Here's a basic example of using react-file-base64 to upload a single file:

import React, { useState } from 'react';
import FileBase64 from 'react-file-base64';

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

  const handleFile = (files) => {
    setFile(files.base64);
  }

  return (
    <div>
      <h1>Upload a file</h1>
      <FileBase64
        multiple={ false }
        onDone={ handleFile }
      />
      { file && <img src={ file } alt="Uploaded file" /> }
    </div>
  );
}

export default App;
Conclusion

react-file-base64 is a simple utility that simplifies handling file uploads in your React application. It's easy to use and can save you a lot of time and effort. Give it a try today!