LoginSignup
18
18

More than 3 years have passed since last update.

FormDataでファイルもオブジェクトも一緒に送る方法

Posted at

ハマった箇所

axiosでファイルも、オブジェクトも送りたいが、オブジェクトが[object Object]になってしまう。

なぜ送れなかったのか?

[FormData.append](https://developer.mozilla.org/ja/docs/Web/API/FormData/append)

The field's value. This can be a USVString or Blob (including subclasses such as File). If none of these are specified the value is converted to a string.

FormDataに追加するときにValueはUSVStringかBlobにしてね、それ以外だと全部テキストにするよとのこと。

その為直接入れるのはNG

送る方法

Axiosでファイルを送る方法

storeFiles(reportId) {
        let formData = new FormData()
        //複数送りたいときは配列にしてあげることも可能
        this.inputs.map(file => {
          formData.append('files[]', file)
        })
        //headerを設定する必要あり。
        let config = {headers: {'content-type': 'multipart/form-data'}}
        axios.post('/path/desu', {
          report_id: reportId
        }), formData, config)
          .then(res => {
            console.log(res.data)
          })
      }

Axiosでファイルとオブジェクトを同じFormDataで送る方法

//送りたいオブジェクト
var examples  = {a: 'task', b: {c: 'small_task'}}

storeFiles(reportId) {
        let formData = new FormData()
        //複数送りたいときは配列にしてあげることも可能
        this.inputs.map(file => {
          formData.append('files[]', file)
        })
        //JSON文字列に変換
        let tasks = JSON.stringfy(this.examples)
        formData.append('tasks', tasks)
        //headerを設定する必要あり。
        let config = {headers: {'content-type': 'multipart/form-data'}}
        axios.post('/path/desu', {
          report_id: reportId
        }), formData, config)
          .then(res => {
            console.log(res.data)
          })
      }

サーバーサイドでJson文字列をデコードしてあげれば配列としてきちんと扱うことができる。

//laravel
public function store(Request $request, $report_id) 
{
    $data = $request->all();
    $task = json_decode($data['tasks']);
    var_dump($task);
    // ['a' => 'task, 'b' => ['c' => 'small_task']]
}
18
18
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
18
18