php - 在 Laravel 中使用 ajax 上传图片
问题描述
我的Laravel
网站中有一个用户信息表单,并尝试使用Ajax
.
刀
<form id="edit_form" enctype="multipart/form-data">
<input type="hidden" name="_token" id="csrf-token" value="{{ Session::token() }}" />
<div class="form-group">
<label>Image</label>
<input id="edit_form_image" type="file" class="form-control" name="user_image">
</div><!-- end form-group -->
<div class="form-group">
<label>Name</label>
<input id="edit_form_name" type="text" class="form-control" value="{{Auth::user()->name}}">
</div><!-- end form-group -->
<button type="button" id="edit_form_submit" class="btn btn-orange">Save Changes</button>
阿贾克斯
$('#edit_form_submit').click(function(event) {
var fd = new FormData();
var edit_form_image = $('#edit_form_image')[0].files;
var edit_form_name = $('#edit_form_name').val();
var token = $('input[name=_token]').val();
fd.append( 'image', edit_form_image );
fd.append( 'name', edit_form_name );
fd.append( '_token', token );
$.ajax({
url:"{{ url('/profile-update') }}",
data: fd,
async:false,
type: 'POST',
processData: false,
contentType: false,
success:function(msg)
{
console.log(msg);
}
});
});
但在我的控制器中,我无法获取图像文件。
控制器
if (request()->hasFile('image'))
{
return "file present";
}
else{
return "file not present";
}
虽然我上传一个图像控制器总是响应“文件不存在”。
错误在哪里?有人帮忙吗?
解决方案
你为什么不命名你的输入标签,因为你需要在 post 方法中发送:
<input name="image" id="edit_form_image" type="file" class="form-control">
<input name="name" id="edit_form_name" type="text" class="form-control" value="{{Auth::user()->name}}">
和,
$("#edit_form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url:"{{ url('/profile-update') }}",
type: "POST",
data: new FormData(this),
processData: false,
contentType: false,
success:function(msg)
{
console.log(msg);
}
});
});
这可能有效。
推荐阅读
- ios - 在 iOS13 中点击日期选择器不会弹出选择器视图
- javascript - 即使我在 EventQueue 中有“非必要”的东西,如何让 NodeJS 终止?
- android - 当反向为真时,颤振列表视图总是滚动到底部
- google-apps-script - 是否可以一次从多张纸上删除行(归档)?
- java - 如何从firestore中的文档中获取特定数据并将其传递给android中的局部变量
- docker - 为什么docker容器更新不稳定?
- asp.net - asp.net文件上传控件上传外部图片URL
- azure - 克服 Azure Vision 读取 API 每秒事务数 (TPS) 限制
- python - 我的代码返回了错误的 if 语句
- sonos - 与家用不同的 Wifi 上的 Sonos 3rd Party 应用程序