LoginSignup
0
0

More than 1 year has passed since last update.

Multipart で APIにリクエストしたとき "Invalid multipart request with 0 mime parts" にハマる

Posted at

やろうとしたこと

Javascript Axios でGoogleDrive にファイルをアップロード

作ったソース

/** Googleドライブ 指定フォルダにファイルをアップロード */
export async function upload(name, mimeType, base64, folderId, accessToken) {
  const body = BOUNDARY + "\r\n"
        + "Content-Type: application/json\r\n\r\n"
        + JSON.stringify({
          title: name,
          mimeType,
          name,
          parents: [folderId],
        }) + "\r\n"
        + BOUNDARY + "\r\n"
        + 'Content-Type: ' + mimeType + "\r\n"
        + "Content-Transfer-Encoding: base64\r\n\r\n"
        + base64 + "\r\n"
        + BOUNDARY + "--";
  const headers = {
    Authorization: `Bearer ${accessToken}`,
    'Content-Type': `multipart/related; boundary="${BOUNDARY}"`,
    accept: '*/*',
  };
  const apiResult = await Axios.post(
    'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart',
    body,
    { headers },
  );

起きた現象

レスポンスが以下

Invalid multipart request with 0 mime parts

判明した原因

BOUNDARY を body で表現するときは、 headers.Content-Type で示した BOUNDARY の先頭に -- がなきゃいけない

解決したソース

/** Googleドライブ 指定フォルダにファイルをアップロード */
export async function upload(name, mimeType, base64, folderId, accessToken) {
  const body = '--' + BOUNDARY + "\r\n"
        + "Content-Type: application/json\r\n\r\n"
        + JSON.stringify({
          title: name,
          mimeType,
          name,
          parents: [folderId],
        }) + "\r\n"
        + '--' + BOUNDARY + "\r\n"
        + 'Content-Type: ' + mimeType + "\r\n"
        + "Content-Transfer-Encoding: base64\r\n\r\n"
        + base64 + "\r\n"
        + '--' + BOUNDARY + "--";
  const headers = {
    Authorization: `Bearer ${accessToken}`,
    'Content-Type': `multipart/related; boundary="${BOUNDARY}"`,
    accept: '*/*',
  };
  const apiResult = await Axios.post(
    'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart',
    body,
    { headers },
  );

まとめ

ハマった時は、うまくいくものと、うまくいかないものを、皿の目でよく見よう
エラーメッセージは英語でも、ちゃんと意味を考えてみよう

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