LoginSignup
1
0

More than 1 year has passed since last update.

multipart/form-dataで個々のデータに対してContent-Typeを指定する。

Posted at

やりたいこと

multipart/form-dataでファイルを送信する際は、FormDataオブジェクトを作ってそれをそのまま送信する。
FormDataオブジェクトを作成するには<form>タグを引数に取ってFormDataを初期化しても良いし、
空のFormDataオブジェクトを作ってそこにデータを足しても良いみたい。
(下記は空のFormDataの例)

// フォームにファイルを指定
let formData = new FormData();
formData.set("uploadFile", file, file.name);

// 送信
let xhr = new XMLHttpRequest();
xhr.open("PUT", "/your/api/url/");
xhr.send(formData);

ただ、こうすると送信時のfileContent-Typeがブラウザで判定されたMIMEタイプで送信されてしまう。
これを明示的に指定したい。

対策

ファイルをtype指定付きでBlobに変換することで、multipart/form-data送信時のContent-Typeも指定した値になる。

let blob = new Blob([file], {type: "application/zip"});

// フォームにblobを指定
let formData = new FormData();
formData.set("uploadFile", blob, file.name);

これはファイルの場合ですが、textや他のデータでもBlobに変換すればContent-Typeを指定できるはず。
(記事末尾の参考記事も参考にしてみてください。)

サンプルコード

upload.html
<!DOCTYPE html>
<html>
<head>
<title>ファイルアップロードテスト</title>
</head>
<body>
<input type="file" onchange="fileChanged(this)"/>
<button id="button">send</button>
<script>
const button = document.getElementById("button");

let file;

// 送信ボタンクリック時
button.onclick = function() {

  let blob = new Blob([file], {type: "application/zip"});

  // フォームにblobを指定
  let formData = new FormData();
  formData.set("uploadFile", blob, file.name);

  // 送信
  let xhr = new XMLHttpRequest();
  xhr.open("PUT", "/your/api/url/");
  xhr.send(formData);
  xhr.onerror = function(e) {
    console.log("ERROR");
    console.log(e);
  }
  xhr.onload = function(e) {
    console.log("LOAD");
    console.log(e);
    console.log(xhr.status);
    console.log(xhr.statusText);
    console.log(xhr.responseText);
    alert(xhr.responseText);
  }
}

// ファイル選択時
function fileChanged(input) {
  file = input.files[0];
  console.log(file);
  console.log(file.name);
}
</script>
</body>
</html>

参考記事

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