尝试在 laravel 中使用 ajax 保存文件,但不知道我的代码出了什么问题



需要在laravel中使用ajax保存文件图像我使用这个代码

控制器

public function store(Request $request)
{
$item = new Item;
// if remove $it_files_path , $it_files_name , $path code work correct 
$it_files_path = $request->file('file'); 
$it_files_name = $it_files_path->getClientOriginalName();
$path = $request->file('file')->storeAs('uploads', $it_files_name, 'public');
$item->it_photo_name = $it_files_name;
$item->it_photo_path = $path;
$item->it_arabic_name = $request->it_arabic_name;
$item->it_english_name = $request->it_english_name;
$item->it_classification = $request->it_classification;
$item->it_weight_gm = $request->it_weight_gm;
$item->it_dim_length = $request->it_dim_length;
$item->it_dim_width = $request->it_dim_width;
$item->it_dim_hight = $request->it_dim_hight;

$item->save();
$item->id = $item->id;
return response()->json(['success' => true , 'item' => $item]);
}

如果我删除下面的注释行工作正常

<<p>视图/strong>
<div class="form-group"> 
<div class="custom-file col-md-12">
<label class="custom-file-label">إختر ملفات المنتج (صور-فيديو-وصف..الخ)</label>
<input type="file" name="file" class="custom-file-input" id="file">
<span class="text-danger" id="fileError"></span>
</div>
</div>

这是我的ajax代码

$.ajax({
url: 'add-new-item',
type: "POST",
data: $('#item,#shp_no_for_it').serialize(),
success: function(response) {
if (response.success){
$('#operation_id').val(response.item.id);
toastr.success('تم إضافة بيانات المنتج بنجاح');
} else {
toastr.error(response.errors.name);
}
}
});

这是我的路由代码

Route::post('add-new-item', [ItemController::class, 'store']);

我不知道我的代码出了什么问题

你必须使用下面的代码

<form method="post" id="form_submit" enctype="multipart/form-data">
@csrf
....
<button type="submit" class="btn btn-success"><i class="fas fa-plus fa-xs"></i>Submit</button>
</form>
$(document).ready(function(){
$('#form_submit').on('submit', function(event){
event.preventDefault();
$.ajax({
url: 'add-new-item',
method:"POST",
data:new FormData(this),
dataType:'JSON',
contentType: false,
cache: false,
processData: false,
success:function(data){
}
})
})
})

你也可以点击这个链接

相关内容

最新更新