12
13

More than 5 years have passed since last update.

axiosを使ってfile属性をPUTで投稿

Posted at

axiosを使ってfile属性をPUTで投稿

[注意]
・FormData()を利用してfile属性を取得する
・POSTで送って、PUTで上書きする


// 呼び出すAPIのURL
        let api_url = 'http://127.0.0.1:8080/';

// file属性にidをつけ、そのidを取得する
        let element = document.getElementById("image_file_path_update_id");

// fileをputもしくはpostしたい場合はFormDataを使用する
// FormDataをせずに送った場合、valueにファイルのパスを指定して送っているので注意する
        let data = new FormData();
// FormDataにimage_file_pathをキーとして、ファイルを追加する
        data.append('image_file_path', element.files[0]);


        // 非同期通信 axios
        axios({
// POSTを指定する
            method: 'POST',
// APIのURLを指定
            url: api_url,
            headers: {
// ファイルを送れるようmultipart/form-datを指定する
                'Content-Type': 'multipart/form-data',
// ここでPUTに置き換える
                'X-HTTP-Method-Override': 'PUT',
            },
// ファイルが入ったデータ
            data: data,
        })
            .then(response => {
                console.log('成功');

            })
            .catch(error => {
                console.log('失敗');
            })

12
13
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
12
13