使用多部分/表单数据标头通过vuejs,laravel和axios上传文件会导致401

时间:2019-10-19 18:36:53

标签: laravel axios

我正在尝试使用axios库上传文件。

axios.post('/images/upload', formData, {
    headers: {
        'Content-Type': 'multipart/form-data'
    }
  }).then( response => console.log(response))
Route::middleware('auth:api')
 ->group( function() {
  Route::post('/images/upload', 'ImageController@store');
})

我收到以下状态码错误

{"message": "unauthenticated"}

当我删除标题部分(即“ multipart / form-data”)时,请求就通过了,但这不是bueno,因为我也需要发送文件。

1 个答案:

答案 0 :(得分:2)

我尝试重现此问题时发现了问题

发送带有抬头的api_token的Bearer抬头

例如

<meta name="csrf-token" content="{{ csrf_token() }}">
<div id="app">
    <input type="file" name="image" id="image" onchange="upload()">
</div>

<script src="{{ asset('js/app.js') }}" defer></script>
<script>
    function upload() {
        let image = document.getElementById('image').files[0];
        let formData = new FormData();
        formData.append('image', image);
        axios.post('/images/upload', formData, {
            headers: {
                'Content-Type': 'multipart/form-data',
                'Authorization': 'Bearer {{ auth()->user()->api_token }}',
            }
        }).then( response => console.log(response))
    }
</script>

假设这样的控制器功能

public function store(Request $request)
{
    $path = $request->file('image')->store('public');
    return $path;
}

您将在响应中获取存储的图像网址

enter image description here

希望这会有所帮助:)