1
2

More than 1 year has passed since last update.

【JavaScript】fileオブジェクトのファイル名を変更したオブジェクトを取得する

Last updated at Posted at 2021-10-26

概要

JavaScriptではFileAPIを使用することで、クライアントPCからのファイルの読み込みを行うことができます。実装はJavaScript でファイルを読み込む方法の記事にのっています。
あまり無いケースだと思いますが、この受け取ったfileオブジェクトでのファイル名を変更する場合、どうすれば良いのかというのをメモ書きします。

対応

fileオブジェクトのファイル名を直接変更することはできません。
対応の一つとして、こちらのstackoverflowの記事にある通り、元のfileオブジェクトをベースにファイル名を変更して、新しくファイルオブジェクトを作成する方法が挙げられます。

実装サンプル

内容は上記のstackoverflowの記事とほぼ同様ですが、元の拡張子を取得して新しいファイルにも同様の拡張子を付与する実装を以下にのせます。

// ファイルはFileAPIで取得している前提
const fileName = inputFile.name;
// ファイルの拡張子を取得
const fileExtention = fileName.substring(fileName.lastIndexOf(".") + 1);
const blob = inputFile.slice(0, inputFile.size, inputFile.type);
// ファイル名称変更後のファイルオブジェクト
const renamedFile = new File([blob], "変更後のファイル名." + fileExtention, {type: inputFile.type});

1
2
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
2