@docflow/react-activestorage-provider

中文文档
1.0.1发布于 2024/04/19MITTypeScriptESM + CJS近 30 天下载 1.3万

A React component that allows easy file upload using ActiveStorage. Updated for React 18

原始使用文档
文档目录6 节
  1. Install
  2. Usage
  3. ActiveStorageProvider Props
  4. RenderProps
  5. DirectUploadProvider
  6. useDirectUpload

@docflow/react-activestorage-provider

NPM

[!NOTE]
This is a fork of react-activestorage-provider, rewritten in TypeScript and modern React (supporting React 18).

There is an important breaking change regarding the uploads array containing finished uploads, see CHANGELOG.md.

Apart from that, this package also extracts the functionality of DirectUploadProvider into a new hook useDirectUpload that you can use to skip the render function. The rest is the same.

ActiveStorage is an amazing addition to Rails 5.2, and as usual the team have made it fantastically simple to use... if you’re generating HTML server-side, that is. This component aims to make it just as easy to use from React.

ActiveStorageProvider handles the direct upload of a file to an ActiveStorage service and the attachment of that file to your model. It uses the render props pattern so you can build your own upload widget.

Install

npm install --save @docflow/react-activestorage-provider

Usage

ActiveStorageProvider makes it easy to add a simple upload button. When you call handleUpload with a FileList or an array of Files, this component creates a Blob record, uploads the file directly to your storage service, and then hits your Rails controller to attach the blob to your model. (If you want to handle the attachment yourself in order to, for example, provide other attributes, see the lower level DirectUploadProvider.)

import ActiveStorageProvider from "@docflow/react-activestorage-provider";

// ...

return (
  <ActiveStorageProvider
    endpoint={{
      path: "/profile",
      model: "User",
      attribute: "avatar",
      method: "PUT",
    }}
    onSubmit={(user) => this.setState({ avatar: user.avatar })}
    render={({ handleUpload, uploads, ready }) => (
      <div>
        <input
          type="file"
          disabled={!ready}
          onChange={(e) => handleUpload(e.currentTarget.files)}
        />

        {uploads.map((upload) => {
          switch (upload.state) {
            case "waiting":
              return (
                <p key={upload.id}>Waiting to upload {upload.file.name}</p>
              );
            case "uploading":
              return (
                <p key={upload.id}>
                  Uploading {upload.file.name}: {upload.progress}%
                </p>
              );
            case "error":
              return (
                <p key={upload.id}>
                  Error uploading {upload.file.name}: {upload.error}
                </p>
              );
            case "finished":
              return (
                <p key={upload.id}>Finished uploading {upload.file.name}</p>
              );
          }
        })}
      </div>
    )}
  />
);

ActiveStorageProvider Props

These are your options for configuring ActiveStorageProvider.

Prop (*required)Description
directUploadsPathstring
The direct uploads path on your Rails app, if you’ve overridden ActiveStorage::DirectUploadsController
endpoint*{ path: string, model: string, attribute: string, method: string, host?: string, port?: string, protocol?: string }
The details for the request to attach the file
headersRecord<string, string>
Optional headers to add to request, can also be used to override default headers
multipleboolean (default: false)
Whether the component should accept multiple files. If true, the model should use has_many_attached
onBeforeBlobRequest(request: { id: string, file: File, xhr: XMLHttpRequest }) => void
A callback that allows you to modify the blob request
onBeforeStorageRequest(request: { id: string, file: File, xhr: XMLHttpRequest }) => void
A callback that allows you to modify the storage request
onError(error: Response) => void
A callback to handle an error (>= 400) response by the server in saving your model
onSubmit*(endpointResponse: unknown) => void
A callback for the server response to successfully saving your model
render*(props: RenderProps) => ReactNode
Render function for your uploader

RenderProps

This is the type of the argument with which your render function will be called.

export type RenderProps = {
  /** false while any file is uploading */
  ready: boolean;
  /** uploads in progress */
  uploads: ActiveStorageFileUpload[];
  /** call to initiate an upload */
  handleUpload: (files: FileList | File[]) => unknown;

  /* or, if you want more granular control... */

  /** call to set list of files to be uploaded */
  handleChooseFiles: (files: FileList | File[]) => unknown;
  /** begin the upload of the files in the list */
  handleBeginUpload: () => unknown;
};

export type CustomHeaders = Record<string, string>;

DirectUploadProvider

ActiveStorageProvider makes it simple to add a quick “upload” button by taking care of both uploading and attaching your file, but it shouldn’t stand in your way if you’re doing something more interesting. If you want to handle the second step, attaching your Blob record to your model, yourself, you can use the lower level DirectUploadProvider. It creates the blob records and uploads the user’s files directly to your storage service, then calls you back with the signed ids of those blobs. Then, you can create or update your model as you need.

function PostForm() {
  function handleAttachment(signedIds) {
    const body = JSON.stringify({ post: { title: ..., images: signedIds }})
    fetch('/posts.json', { method: 'POST', body })
  }

  return (
    <DirectUploadProvider onSuccess={handleAttachment} render={...} />
  )
}

DirectUploadProvider is a named export, so

import { DirectUploadProvider } from "@docflow/react-activestorage-provider";

and use it with the following props:

Prop (*required)Description
directUploadsPathstring
The direct uploads path on your Rails app, if you’ve overridden ActiveStorage::DirectUploadsController
headersRecord<string, string>
Optional headers to add to request
onBeforeBlobRequest(request: { id: string, file: File, xhr: XMLHttpRequest }) => void
A callback that allows you to modify the blob request
onBeforeStorageRequest(request: { id: string, file: File, xhr: XMLHttpRequest }) => void
A callback that allows you to modify the storage request
onSuccess*(signedIds: string[]) => void
The callback that will be called with the signed ids of the files after the upload is complete
origin{ host?: string, port?: string, protocol?: string }
The origin of your rails server. Defaults to where your React app is running
render*(props: RenderProps) => ReactNode
Render function for your uploader

useDirectUpload

If you want to use the functionality of DirectUploadProvider without the hassle of the render function, use this hook. It takes all the same props as DirectUploadProvider, except for render, and returns the same thing as the render function accepts as an argument.

import { useDirectUpload } from "@docflow/react-activestorage-provider";

function Uploader() {
  const { handleUpload } = useDirectUpload({
    onSuccess: (signedIds) => console.log(signedIds),
  });

  return (
    <input
      type="file"
      onChange={(e) => e.target.files && handleUpload(e.target.files)}
    />
  );
}

版本与发布记录

@docflow/react-activestorage-provider 共发布 2 个版本,首次发布于 2024/03/30;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.0.1latest2024/04/192 年前
1.0.02024/03/302 年前

关于 @docflow/react-activestorage-provider 的常见问题

@docflow/react-activestorage-provider 是什么?

A React component that allows easy file upload using ActiveStorage. Updated for React 18

如何安装 @docflow/react-activestorage-provider?

在项目目录运行 npm install @docflow/react-activestorage-provider,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(>= 16.8.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@docflow/react-activestorage-provider 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@docflow/react-activestorage-provider 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@docflow/react-activestorage-provider 可以商用吗?

@docflow/react-activestorage-provider 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@docflow/react-activestorage-provider 的下载量有多少?

根据 npm 官方下载统计,@docflow/react-activestorage-provider 在 2026/10/13 – 2026/11/11 这 30 天内被下载 12,855 次,日均约 429 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@docflow/react-activestorage-provider 还在维护吗?

最新版本 1.0.1 发布于 2024/04/19(2 年前);至今共发布 2 个版本,其中过去 12 个月发布了 0 个;首次发布于 2024/03/30。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。