使用axios中的put方法上传formdata表单,后端laravel接收到的数据为空
时间: 2024-02-28 12:54:28 浏览: 20
如果您在使用 Axios 中的 PUT 方法上传 FormData 表单时,后端 Laravel 接收到的数据为空,可能是因为 Axios 默认会将请求的 Content-Type 设置为 application/json,而不是 multipart/form-data。
要解决这个问题,可以手动将 Content-Type 设置为 multipart/form-data,例如:
```javascript
const formData = new FormData();
formData.append('file', file);
axios.put('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
console.log(response);
}).catch(error => {
console.log(error);
});
```
在 Laravel 中,可以使用 Request 对象的 file 方法来接收上传的文件,例如:
```php
$file = $request->file('file');
if ($file) {
$filename = $file->getClientOriginalName();
$path = $file->storeAs('uploads', $filename);
return response()->json(['success' => true, 'path' => $path]);
} else {
return response()->json(['success' => false, 'message' => '上传文件为空']);
}
```
这个 PHP 脚本会将上传的文件保存到服务器上的 uploads 目录中,并返回上传成功的消息。