1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Reactでvideoのアップロードフォームを作る

Posted at

はじめに

今回は、Reactでvideo(動画ファイル)をアップロードし、そのファイルのプレビューを行うことのできるフォームを紹介します。

コード全文

  const inputRef = useRef();
  const [source, setSource] = useState();
  const [file,setFile] = useState();

  const handleFileChange = (event) => {
    const file = event.target.files[0];
    const url = URL.createObjectURL(file);
    setFile(file);
    setSource(url);
  };

  const handleChoose = (event) => {
    inputRef.current.click();
  };

  return (
    <div className="VideoInput">
      <input
        ref={inputRef}
        className="VideoInput_input"
        type="file"
        onChange={handleFileChange}
        accept=".mov,.mp4"
      />
      {!source && <button onClick={handleChoose}>動画を選択</button>}
      {source && (
        <video
          className="VideoInput_video"
          width="100%"
          height="400px"
          controls
          src={source}
        />
      )}
      <div className="VideoInput_footer">
        {source || "ファイルが選択されていません"}
      </div>
    </div>
  );
cssはこちら

.VideoInput {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border: 1px solid #ddd;
}

.VideoInput_input {
  display: none;
}

.VideoInput_video {
  display: block;
  margin: 0;
}

.VideoInput_footer {
  background: #eee;
  width: 100%;
  min-height: 40px;
  line-height: 40px;
  text-align: center;
}

要点解説

プレビューを可能にしているのは、主にsouceのおかげです。

const url = URL.createObjectURL(file);
setSource(url);

URL.createObjectURLというメソッドは、Fileなどを引数に取って、videoimgタグで表示できるurlを生成してくれます。

生成されたurlをsetSource(url);のようにするとコンポーネントの再描画が走り、

{source && (
        <video
          className="VideoInput_video"
          width="100%"
          height="400px"
          controls
          src={source}
        />
      )}

source && ~~、つまりsourcenullでは無くなった(trueである)時に左辺が評価され、生成されたurlがsrcに入ったvideoが表示されるというわけです。

また、これはおまけですが、
inputタグにあるaccept=".mov,.mp4"で、inputできるファイルの拡張子を設定することができます。

ファイル自体はfileに保存されているので、postする時などはこちらをつかいます。

画像の場合も同じような感じで書けますので、ぜひやってみてください!

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?